开发者

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


while(!Console.KeyAvailable)
{
    //do work
}


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


HAVE A BOOLEAN VARIABLE.

like bool flag = true; while(flag) { your code; }

when the key is pressed, change the flag to false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜