C# Make Program Wait For Button To Be Pressed

后端 未结 3 703
有刺的猬
有刺的猬 2021-01-18 08:04

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

3条回答
  •  执念已碎
    2021-01-18 08:15

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

    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
    }
    

    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.

    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.

    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.

    So in pseudo code you have:

    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
        }
    }
    

提交回复
热议问题