7
4

4 回答 4

7

控制台有一个方法,您可以检查标准输入是否已被重定向。

public static bool IsInputRedirected { get; }
于 2013-11-12T21:00:54.997 回答
3

您的程序抛出该异常是因为,Console.ReadKey(true);MSDN 文档中所述:

如果intercept参数为true,则被按下的按键被拦截,并且不显示在控制台窗口中;否则,显示按下的键。

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

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

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

或者

Console.ReadLine();

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

ConsoleKeyInfo cki;
Console.Write("Press any key to continue . . . ");
cki = Console.ReadKey(true);
于 2013-11-12T21:04:19.720 回答
3

我遇到了同样的错误。

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

项目名称->右键单击->属性

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

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

于 2017-11-01T07:37:43.890 回答
0
/// <summary>
/// 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.
/// </summary>
/// <param name="key">The key that the Console will wait for. If this parameter is omitted the Enter key is used.</param>    
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) { }
}
于 2013-11-12T20:58:55.007 回答