C#循环和按键中断循环

Kyl*_*yle 4 c# infinite-loop winforms

我的代码包含这样的内容:

{
    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;
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望这个循环不断循环,直到我调用一个按键停止.

我不能做什么我写这个循环的代码,或者我应该采取不同的方式来解决这个问题.

提前致谢

spe*_*der 7

while(!Console.KeyAvailable)
{
    //do work
}
Run Code Online (Sandbox Code Playgroud)

  • 延迟信息("它是一个winform")使这个答案无效. (3认同)
  • 不过,由于这是对控制台应用程序执行此操作的好方法,因此您从我这里获得了+1(其他正在寻找“ keypress loop”的人可能会对您的回答感兴趣) (2认同)

小智 -2

有一个布尔变量。

就像 bool flag = true; while(flag) { 你的代码; }

当按下该键时,将标志更改为 false。