再次按下空格键怎么编程

时间:2025-02-26 21:53:48 明星趣事

如果您想要在按下空格键时暂停程序,然后在再次按下空格键时恢复程序的执行,可以使用以下代码示例:

```csharp

using System;

namespace ConsoleApp1

{

class Program

{

static void Main(string[] args)

{

bool isPaused = false;

while (true)

{

Console.WriteLine("按空格键暂停或继续...");

if (!isPaused && Console.KeyAvailable)

{

ConsoleKeyInfo keyInfo = Console.ReadKey();

if (keyInfo.Key == ConsoleKey.Space)

{

isPaused = !isPaused;

}

}

if (!isPaused)

{

// 在这里放置您的代码

for (int i = 0; i <= 100000; i++)

{

Console.WriteLine(i);

System.Threading.Thread.Sleep(1); // 模拟耗时操作

}

}

}

}

}

}

```

在这个示例中,我们使用了一个布尔变量 `isPaused` 来跟踪程序是否应该暂停。当 `isPaused` 为 `false` 时,程序会正常执行。当按下空格键时,`isPaused` 的值会切换,从而控制程序的暂停和继续。

请注意,这个示例是针对控制台应用程序的,如果您正在使用图形用户界面(GUI)应用程序,您可能需要使用不同的方法来处理键盘事件。