Reputation: 13
I would like to force whatever the user has typed to be entered after a certain time. I've been using something like this, but it has problems.
string input = Console.ReadLine();
while (repeat == true)
{
if (Time has passed)
{
SendKeys.Send("{ENTER}");
repeat = false;
}
else
repeat = true;
}
The problem is that it just stays at ReadLine until the user presses enter. I also don't want to use ReadKey, because I would like it to be able to contain more than one character.
Upvotes: 1
Views: 353
Reputation: 1362
This will wait 5 seconds, appending any keypresses to the string input
. It shows each letter as it is typed. Finally it exits loop and prints input for confirmation.
var timer = new Timer(5000);
bool timeUp = false;
string input = "";
timer.Elapsed += (o,e) => { timeUp = true; };
timer.Enabled = true;
while(!timeUp) {
if (Console.KeyAvailable)
{
char pressed = Console.ReadKey(true).KeyChar;
Console.Write(pressed);
input+=pressed;
}
System.Threading.Thread.Sleep(100);
}
Console.WriteLine(input);
Upvotes: 0
Reputation: 8708
I'd use a task and wait for it 5 seconds.
static void Main(string[] args)
{
List<ConsoleKeyInfo> userInput = new List<ConsoleKeyInfo>();
var userInputTask = Task.Run(() =>
{
while (true)
userInput.Add(Console.ReadKey(true));
});
userInputTask.Wait(5000);
string userInputStr = new string(userInput.Select(p => p.KeyChar).ToArray());
Console.WriteLine("Time's up: you pressed '{0}'", userInputStr);
Console.ReadLine();
}
Upvotes: 1