简体   繁体   中英

Need While Loop to pause to allow user to press a button in c#

I need help stopping this loop from constantly looping, i need it to give the user time to choose something in the new form it opens up but currently it just opens a whole load of them and doesn't stop.

while (Convert.ToInt32(PlayerHP[PlayerNo]) > 0 && Convert.ToInt32(PlayerHP[PlayerNo+1]) > 0){
    ChooseAttack();
    PlayerHP[PlayerNo+1] = (Convert.ToInt32(PlayerHP[PlayerNo+1]) - Damage()).ToString();
    lblHPP1.Text = PlayerHP[0];
    lblHPP2.Text = PlayerHP[1];
    PlayerNo = ((PlayerNo+1)%2);
    Application.DoEvents();
}

I've been experimenting with the "Application.DoEvents()" line but whereever i place it it doesnt do anything.

I don't see a form anywhere, but expect that somewhere in that ChooseAttack(); call you have some code that looks like this:

frmChoose.Show();

And all you need to do is change it to this:

frmChoose.ShowDialog();

I would push the loop out onto a timer thread so you can control the "loop" externally. The speed at which the loop runs would be the timeout time of the timer.

For more clarity, you would no longer have a 'while' statement, more of an if at the top of the timer's call back method to check your conditions. The actual looping part of it would be taken care of by the timer executing over and over.

Depending on which timer you choose, when you click a button on the form, you would just say Timer.Enabled = false; or something similar.

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