Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# loop and keypress break loop

My code consists of something like this:

{
    var comeback = Cursor.Position;
    code goes here
    code goes here
    code goes here
    code goes here
    code goes here
    code goes here
    Cursor.Position = restart;
}

Now, I wish to have this continuously looped until such time as I invoke a keypress to stop.

What I cannot do i write the code for this loop, or is there a different way I should be going about this.

Thanks in advance

like image 306
Kyle Avatar asked Apr 25 '11 13:04

Kyle


2 Answers

while(!Console.KeyAvailable)
{
    //do work
}
like image 133
spender Avatar answered Sep 24 '22 13:09

spender


since OP thanked me for the first answer, I'll keep that as reference below..

consider having a background thread that does the loop. Then add a key listener in your project (if you have visual studio, open up the properties tab and check out events) by double clicking the KeyPressed event. You'll get something like this:

    private bool keyPressed;

    public MyClass() {
        keyPressed = false;
        Thread thread = new Thread(myLoop);
        thread.Start();
    }

    private void myLoop() {
        while (!keyPressed) {
            // do work
        }
    }

    private void MyClass_KeyPress(object sender, KeyPressEventArgs e) {
        keyPressed = true;
    }
}

Consider having a thread that listen for a keypress and then set a flag in your program that you check in your loop.

for instance Untested

bool keyPressed = false;
...    
void KeyPressed(){
    Console.ReadKey();
    keyPressed = true;
}
...
Thread t = new Thread(KeyPressed);
t.Start();
...
while (!keyPressed){
    // your loop goes here
    // or you can check the value of keyPressed while you're in your loop
    if (keyPressed){
        break;
    }
    ...
}
like image 33
default Avatar answered Sep 21 '22 13:09

default