使用< nul调用时C#ReadKey崩溃的控制台应用程序 [英] C# ReadKey crashing console app when called using <nul
问题描述
因此,我决定开始使用C#进行编程,而我要做的一件事就是创建一个"pausec.exe"(pausec.exe克隆).它可以工作,但是在调用时像这样:
So I decided to start programming in C#, and one of the things I did was to create a "pausec.exe" (a pause.exe clone). It works, but when calling it like:
< nul pausec
...崩溃.我收到的错误-从西班牙语翻译成我所知的错误-如下:
...it crashes. The error I get - translated from Spanish to the best of my knowledge - goes like this:
未处理的异常:System.InvalidOperationException:无法读取 当任何应用程序没有控制台或当 控制台输入已从文件重定向.尝试使用Console.Read.
Unhandled exception: System.InvalidOperationException: Can't read keys when any of the applications doesn't have a console or when the console input has been redirected from a file. Try with Console.Read.
然后stacktrace告诉我错误在哪里:
And the stacktrace telling me where the error is:
in System.Console.ReadKey(Boolean intercept)
in System.Console.ReadKey()
in pausec.Program.Main(String[] args)
这是我正在运行的代码:
This is the code I'm running:
using System;
namespace pausec
{
class Program
{
static void Main(string[] args)
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.Write("\n");
}
}
}
我想知道是否有解决方法,甚至可能是使用< nul
时忽略ReadKey
的方法?
I'm wondering if there's a workaround for this, maybe even a way to ignore the ReadKey
when using < nul
?
我们将不胜感激.
预先感谢
Any help is appreciated.
Thanks in advance
更新:找到了一种方法,消除了拦截(如阿尔贝托·索拉诺建议)然后添加Console.Write("\b \b");
在ReadKey
方法之后,它可以工作.奇怪的是,当我将应用程序复制到桌面时,它不会等待用户输入并自动关闭.
UPDATE: Found a way, by removing the intercept (as Alberto Solano suggested) and then, adding Console.Write("\b \b");
after the ReadKey
method, it works. Weird thing is, when I copy the application to my desktop, it doesn't wait for user input and closes automatically.
更新2 :现在可以正常使用.谢谢大家的回答!
UPDATE 2: It works perfectly now. Thank you all for answering!
推荐答案
控制台中有一种方法可以检查stdin是否已重定向.
The console has a method that you can check to see if stdin has been redirected.
public static bool IsInputRedirected { get; }
这篇关于使用< nul调用时C#ReadKey崩溃的控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!