C#make程序等待按钮是pressed [英] C# Make Program Wait For Button To Be Pressed

查看:192
本文介绍了C#make程序等待按钮是pressed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使程序等待一个按键是pssed $ P $继续之前,我试图创建一个while循环,直到单击该按钮并设置一个布尔为true,while循环结束有它循环,这使得它的崩溃

I want to make the program wait for a button to be pressed before it continues, I tried creating a while loop and having it loop until the button is clicked and sets a bool to true for the while loop to end, this made it crash

   while (!Redpress)
                    {
                        //I'd like the wait here
                    }
                    Redpress = false;

这并不重要,而是否存在,只要在程序中设置红preSS假前等待按钮preSS ...任何想法?

It doesn't matter whether or not the while is there, as long as the program waits for the button press before setting "Redpress" to false... Any Ideas?

推荐答案

使用事件 - 这就是他们设计的。

Use events - it's what they're designed for.

您不需要在 Button_Click 事件处理程序使用一个布尔变量为此打电话给你的code:

You don't need to use a boolean variable for this in the Button_Click event handler call your code:

private void Button_Click(object sender, EventArgs e)
{
    // The code you need to execute when the button is pressed
}

由于@trickdev指出,您将需要订阅这个事件,但如果你使用Visual Studio中的活动窗口,将增加必要的code - 包括空处理程序 - 为你

As @trickdev points out you will need to subscribe to this event but if you use the Events window in Visual Studio it will add the necessary code - including the empty handler - for you.

随着你一直在等待,直到下一个东西事件驱动程序发生。所以你的情况(如果我理解您的应用程序正确)当您启动程序应该简单地告诉第一个按钮闪烁N次。如果你写的事件,那么应用程序将返回到等待状态,一旦code已经完成。

With event driven programs you are always waiting until the next "thing" happens. So in your case (if I've understood your application correctly) when you start the program it should simply tell the first button to flash "N" times. If you write that as event then the application will return to the waiting state once the code has completed.

然后在按钮单击事件处理 - 您可以订阅所有按钮同一事件 - 你可以检查正确的按钮已被pressed然后告诉下按钮闪烁。如果错了按钮是pressed然后显示一个合适的消息。

Then in the button click event handler - you can subscribe all the buttons to the same event - you can check that the correct button has been pressed and then tell the next button to flash. If the wrong button was pressed then display a suitable message.

因此​​,在伪code你有:

So in pseudo code you have:

public class Form
{
    Initialise()
    {
        // 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
    }
}

这篇关于C#make程序等待按钮是pressed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆