使用<nul调用C#ReadKey崩溃控制台应用程序

所以我决定用C#开始编程,我做的一件事就是创建一个“pausec.exe”(pause.exe克隆)。 它有效,但在调用它时:
<nul pausec
……它崩溃了 我得到的错误 – 从西class牙语翻译到我所知的最佳 – 是这样的:

未处理的exception:System.InvalidOperationException:当任何应用程序没有控制台或控制台输入已从文件重定向时,无法读取键。 尝试使用Console.Read。

然后一个块告诉我错误在哪里:

in System.Console.ReadKey(Boolean intercept) in System.Console.ReadKey() in pausec.Program.Main(String[] args) 

这是我正在运行的代码:

 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的方法?

任何帮助表示赞赏。
提前致谢

编辑:找到一种方法,通过删除拦截(如Alberto Solano建议)然后添加Console.Write("\b \b"); 在ReadKey命令之后它可以工作。 奇怪的是,当我将应用程序复制到我的桌面时,它不会等待用户输入并自动关闭。

编辑2:它现在完美运作。 谢谢大家回答!

控制台有一个方法,您可以检查是否已重定向stdin。

 public static bool IsInputRedirected { get; } 

您的程序抛出该exception,因为使用Console.ReadKey(true); ,如MSDN文档中所述 :

如果拦截参数为真,则按下的键被截取,不会显示在控制台窗口中; 否则,显示按下的键。

您没有阅读或“聆听”键盘中按下的任何键,然后没有键来拦截和不显示在控制台窗口中。

如果您只想按任意键关闭程序,请使用:

 Console.ReadKey(); //this won't intercept any key pressed 

要么

 Console.ReadLine(); 

更新:您在评论中询问如何隐藏用户按下的键。 这段代码应该可以解决问题:

 ConsoleKeyInfo cki; Console.Write("Press any key to continue . . . "); cki = Console.ReadKey(true); 

我遇到了同样的错误。

所以我刚检查了我的项目输出类型。

ProjectName-> RightClick->属性

在那里你可以看到你的输出类型。

所以我将其更改为控制台应用程序,因为在我的情况下它似乎是以前的Windows应用程序。 然后它的工作正常。

 ///  /// Written by fredrik92 (http://social.msdn.microsoft.com/Forums/vstudio/en-US/08163199-0a5d-4057-8aa9-3a0a013800c7/how-to-write-a-command-like-pause-to-console?forum=csharpgeneral) /// Writes a message to the console prompting the user to press a certain key in order to exit the current program. /// This procedure intercepts all keys that are pressed, so that nothing is displayed in the Console. By default the /// Enter key is used as the key that has to be pressed. ///  /// The key that the Console will wait for. If this parameter is omitted the Enter key is used. public static void WriteKeyPressForExit(ConsoleKey key = ConsoleKey.Enter) { Console.WriteLine(); Console.WriteLine("Press the {0} key on your keyboard to exit . . .", key); while (Console.ReadKey(intercept: true).Key != key) { } }