C#循环和按键中断循环

| 我的代码包含以下内容:
{
    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;
}
现在,我希望它不断循环播放,直到我按下按键停止。 我无法为此循环编写代码,或者我应该采用其他方法处理此循环。 提前致谢     
已邀请:
while(!Console.KeyAvailable)
{
    //do work
}
    
由于OP感谢我的第一个回答,因此我将其保留为以下参考。 考虑使用执行循环的后台线程。然后通过双击KeyPressed事件在项目中添加一个键侦听器(如果您有Visual Studio,则打开属性选项卡并签出事件)。您会得到以下信息:
    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;
    }
}
考虑让一个线程监听按键,然后在您的程序中设置一个标志来检查循环。 例如未经测试
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;
    }
    ...
}
    
具有布尔值变量。 喜欢 布尔标志= true; while(标志) { 您的代码; } 当按下键时,将标志更改为false。     

要回复问题请先登录注册