tyj*_*enn 9 c# console-application raspberry-pi .net-core
我正在编写.NET Core控制台应用程序.我想将控制台输入限制为每个输入的特定数量的最大字符.我有一些代码通过构建一个字符串Console.ReadKey()而不是Console.ReadLine()Everything在Windows上完美地测试它来实现这一点.然后,当我部署到运行Raspbian的Raspberry Pi 3时,我很快遇到了各种各样的问题.我记得Linux处理行结尾的方式与Windows不同,似乎退格处理方式也不同.我改变了处理它们的方式,取消了ConsoleKey而不是字符,换行问题消失了,但退格只是有时会注册.此外,有时字符会输出到我输入框外的控制台,即使我将ReadKey设置为不自行输出到控制台.我错过了Linux处理控制台输入的方法吗?
//I replaced my calls to Console.ReadLine() with this. The limit is the
//max number of characters that can be entered in the console.
public static string ReadChars(int limit)
{
string str = string.Empty; //all the input so far
int left = Console.CursorLeft; //store cursor position for re-outputting
int top = Console.CursorTop;
while (true) //keep checking for key events
{
if (Console.KeyAvailable)
{
//true to intercept input and not output to console
//normally. This sometimes fails and outputs anyway.
ConsoleKeyInfo c = Console.ReadKey(true);
if (c.Key == ConsoleKey.Enter) //stop input on Enter key
break;
if (c.Key == ConsoleKey.Backspace) //remove last char on Backspace
{
if (str != "")
{
tr = str.Substring(0, str.Length - 1);
}
}
else if (c.Key != ConsoleKey.Tab && str.Length < limit)
{
//don't allow tabs or exceeding the max size
str += c.KeyChar;
}
else
{
//ignore tabs and when the limit is exceeded
continue;
}
Console.SetCursorPosition(left, top);
string padding = ""; //padding clears unused chars in field
for (int i = 0; i < limit - str.Length; i++)
{
padding += " ";
}
//output this way instead
Console.Write(str + padding);
}
}
return str;
}
Run Code Online (Sandbox Code Playgroud)
我认为 Stephen Toub 在这个 GitHub 问题中的评论暴露了根本问题:
您可能会想到这样一个事实,即我们现在仅在 ReadKey(intercept: true) 调用期间禁用回显,因此在用户键入和您调用 ReadKey(intercept: true) 之间的竞争中,即使在你希望它不会,但你不会失去击键。
这是冰冷的安慰,但却是准确的。这是一场很难获胜的比赛。核心问题是 Linux 终端的工作方式与 Windows 控制台非常不同。它的操作方式更像是 20 世纪 70 年代的电传打字机。你敲击键盘,不管计算机是否注意到你输入的内容,电传打字机只是回显你在纸上敲打的内容。直到您按下 Enter 键,计算机才开始处理文本。
与 Windows 控制台非常不同,它要求程序有一个活动的 Read 调用来回显任何键入的文本。
所以这与控制台 API 是一个非常根本的不匹配。它需要一个Echo属性来让您有希望正确地执行此操作。因此,您可以在开始接受输入并自行处理回声之前将其设置为false 。这仍然是一场竞赛,但至少你有机会清除任何预先输入的文本。
您现在拥有的唯一还算不错的解决方法是在启动程序之前禁用回显。要求您通过您的方法完成所有输入。
| 归档时间: |
|
| 查看次数: |
774 次 |
| 最近记录: |