Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
*.user
project.lock.json
.vs/
.idea/
9 changes: 9 additions & 0 deletions src/ReadLine.Demo/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
Expand All @@ -20,6 +22,13 @@ public static void Main(string[] args)

input = ReadLine.ReadPassword("Enter Password> ");
Console.WriteLine(input);

var src = new CancellationTokenSource();
src.CancelAfter(3000);
input = ReadLine.ReadAsync("You have 3 sec to prompt: ", cancellationToken: src.Token).Result;
if (!src.IsCancellationRequested)
Console.WriteLine(input);
src.Dispose();
}
}

Expand Down
49 changes: 49 additions & 0 deletions src/ReadLine/ReadLine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using Internal.ReadLine.Abstractions;

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace System
{
Expand Down Expand Up @@ -39,6 +41,25 @@ public static string Read(string prompt = "", string @default = "")
return text;
}

public static async Task<string> ReadAsync(string prompt = "", string @default = "", CancellationToken cancellationToken = default)
{
Console.Write(prompt);
KeyHandler keyHandler = new KeyHandler(new Console2(), _history, AutoCompletionHandler);
string text = await GetTextAsync(keyHandler, cancellationToken);
if (String.IsNullOrWhiteSpace(text) && !String.IsNullOrWhiteSpace(@default))
{
text = @default;
}
else
{
if (HistoryEnabled)
_history.Add(text);
}
if (cancellationToken.IsCancellationRequested)
Console.WriteLine("");
return text;
}

public static string ReadPassword(string prompt = "")
{
Console.Write(prompt);
Expand All @@ -58,5 +79,33 @@ private static string GetText(KeyHandler keyHandler)
Console.WriteLine();
return keyHandler.Text;
}

private static async Task<string> GetTextAsync(KeyHandler keyHandler, CancellationToken cancellationToken = default)
{
Task.Run(() =>
{
while (!Console.KeyAvailable)
{
if (cancellationToken.IsCancellationRequested)
return;
Thread.Sleep(50);
}
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
keyHandler.Handle(keyInfo);
while (!Console.KeyAvailable)
{
if (cancellationToken.IsCancellationRequested)
return;
Thread.Sleep(50);
}
keyInfo = Console.ReadKey(true);
}

Console.WriteLine();
}).Wait();
return keyHandler.Text;
}
}
}