I am trying to do a press Q to quit thing in the console window. I dont like my current implementation. Is there a way i can async or use a callback to get keys from the con
I didn't find any of the exisiting answers entirely satisfactory so I wrote my own, to work with TAP and .Net 4.5.
///
/// Obtains the next character or function key pressed by the user
/// asynchronously. The pressed key is displayed in the console window.
///
///
/// The cancellation token that can be used to cancel the read.
///
///
/// The number of milliseconds to wait between polling the
/// property.
///
/// Information describing what key was pressed.
///
/// Thrown when the read is cancelled by the user input (Ctrl+C etc.)
/// or when cancellation is signalled via
/// the passed .
///
public static async Task ReadKeyAsync(
CancellationToken cancellationToken,
int responsiveness = 100)
{
var cancelPressed = false;
var cancelWatcher = new ConsoleCancelEventHandler(
(sender, args) => { cancelPressed = true; });
Console.CancelKeyPress += cancelWatcher;
try
{
while (!cancelPressed && !cancellationToken.IsCancellationRequested)
{
if (Console.KeyAvailable)
{
return Console.ReadKey();
}
await Task.Delay(
responsiveness,
cancellationToken);
}
if (cancelPressed)
{
throw new TaskCanceledException(
"Readkey canceled by user input.");
}
throw new TaskCanceledException();
}
finally
{
Console.CancelKeyPress -= cancelWatcher;
}
}