-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathTestConsole.TestConsoleReader.cs
65 lines (57 loc) · 2.24 KB
/
TestConsole.TestConsoleReader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using CommandDotNet.Prompts;
using CommandDotNet.Rendering;
namespace CommandDotNet.TestTools
{
public partial class TestConsole
{
private class TestConsoleReader : IConsoleReader
{
private readonly IConsoleWriter _standardOut;
private readonly Func<string?>? _onReadLine;
private readonly Func<ConsoleKeyInfo>? _onReadKey;
public TestConsoleReader(IConsoleWriter standardOut, Func<string?>? onReadLine, Func<ConsoleKeyInfo>? onReadKey)
{
_standardOut = standardOut ?? throw new ArgumentNullException(nameof(standardOut));
_onReadLine = onReadLine;
_onReadKey = onReadKey;
}
public bool KeyAvailable { get; }
public bool NumberLock { get; }
public bool CapsLock { get; }
public bool TreatControlCAsInput { get; set; }
/// <summary>
/// Read a key from the input
/// </summary>
/// <param name="intercept">When true, the key is not displayed in the output</param>
/// <returns></returns>
public ConsoleKeyInfo ReadKey(bool intercept)
{
ConsoleKeyInfo consoleKeyInfo;
do
{
consoleKeyInfo = _onReadKey?.Invoke()
?? new ConsoleKeyInfo('\u0000', ConsoleKey.Enter, false, false, false);
// mimic System.Console which does not interrupt during ReadKey
// and does not return Ctrl+C unless TreatControlCAsInput == true.
} while (!TreatControlCAsInput && consoleKeyInfo.IsCtrlC());
if (!intercept)
{
if (consoleKeyInfo.Key == ConsoleKey.Enter)
{
_standardOut.WriteLine("");
}
else
{
_standardOut.Write(consoleKeyInfo.KeyChar.ToString());
}
}
return consoleKeyInfo;
}
public string? ReadLine()
{
return _onReadLine?.Invoke();
}
}
}
}