user2502919
user2502919

Reputation: 1

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.

Upvotes: 0

Views: 102

Answers (2)

K0D4
K0D4

Reputation: 2623

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.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

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();

Upvotes: 2

Related Questions