13th
Мар

Как в C# прервать работу цикла при нажатии клавиши?

Posted by Chas under Пост-обзор

Есть цикл, например этот:

while(true)
{
Console.Write("Текст ");
}
Console.Write("Цикл завершился");
Console.ReadKey();

Цикл работает вечно. Нужно что бы он прерывался при нажатии какой то клавиши, например «Q» и продолжалась работа программы. Как это можно сделать?

Serge_Bliznykov:

C#  Копировать код
// This example demonstrates the Console.KeyAvailable property.
using System;
using System.Threading;

class Sample
{
public static void Main()
{
ConsoleKeyInfo cki = new ConsoleKeyInfo();

do {
Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");

// Your code could perform some useful task in the following loop. However,
// for the sake of this example we'll merely pause for a quarter second.

while (Console.KeyAvailable == false)
Thread.Sleep(250); // Loop until input is entered.
cki = Console.ReadKey(true);
Console.WriteLine("You pressed the '{0}' key.", cki.Key);
} while(cki.Key != ConsoleKey.X);
}
}

или

 ConsoleKeyInfo cki = new ConsoleKeyInfo();

while (true)
{
Console.Write("Текст ");
if (Console.KeyAvailable == true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.X)
{
break;
}
}
}
Console.Write("Цикл завершился");
Console.ReadKey();

тема на форуме

Похожие статьи

Теги: