[英]ReadKey while key is not pressed do something
我试图运行我的代码,直到Esc被按下。 因此我在控制台中使用ReadKey
var input = Console.ReadKey();
do
{
} while (input.Key != ConsoleKey.Escape);
但是在“ConsoleKey”它说,在'bool'中不可能使用ConsoleKey。 我该如何解决这个问题? 或者我应该使用什么呢?
试试这个:
ConsoleKeyInfo input;
do
{
input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);
是否有特殊原因要使用ESC键而不是传统的CTRL + C ?
您可以为后者挂接Console.CancelKeyPress
事件,它在命令行界面世界中是标准的。
Console.ReadKey()
是阻塞的,在某些循环中可能会出现问题。 我们来看这个例子:
using System.Threading;
using System.Threading.Tasks;
CancellationTokenSource cts;
public void Run()
{
cts = new CancellationTokenSource();
var task = new Task(DoSomething, cts.Token);
task.Start();
while (!task.IsCompleted)
{
var keyInput = Console.ReadKey(true);
if (keyInput.Key == ConsoleKey.Escape)
{
Console.WriteLine("Escape was pressed, cancelling...");
cts.Cancel();
}
}
Console.WriteLine("Done.");
}
void DoSomething()
{
var count = 0;
while (!cts.IsCancellationRequested)
{
Thread.Sleep(1000);
count++;
Console.WriteLine("Background task has ticked ({0}).", count.ToString());
}
}
这将使用Task
执行一些后台工作,同时等待按下ESC 。 取消工作正常,但在完成(取消)后它将再次停留在Console.ReadKey()
)上。
您可以使用Win32 API,例如GetKeyboardState
并检查密钥代码,因为它没有阻塞。 但是,我建议使用CancelKeyPress
事件( CTRL + C ):
void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Cancelling...");
cts.Cancel();
e.Cancel = true; // Do not terminate immediately!
}
ConsoleKeyInfo input;
do
{
input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);
或更短
while (Console.ReadKey().Key != ConsoleKey.Escape){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.