所以我决定开始用C#编程,我做的一件事就是创建一个"pausec.exe"(pause.exe克隆).它有效,但在调用它时:
< nul pausec
Run Code Online (Sandbox Code Playgroud)
......它崩溃了 我得到的错误 - 从西班牙语翻译到我所知的最佳 - 是这样的:
未处理的异常:System.InvalidOperationException:当任何应用程序没有控制台或控制台输入已从文件重定向时,无法读取键.尝试使用Console.Read.
堆栈跟踪告诉我错误在哪里:
in System.Console.ReadKey(Boolean intercept)
in System.Console.ReadKey()
in pausec.Program.Main(String[] args)
Run Code Online (Sandbox Code Playgroud)
这是我正在运行的代码:
using System;
namespace pausec
{
class Program
{
static void Main(string[] args)
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.Write("\n");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一个解决方法,甚至可能忽略使用ReadKey时的方法< nul?
任何帮助表示赞赏.
提前致谢
更新:找到一种方法,通过删除拦截(如Alberto Solano建议的那样)然后,Console.Write("\b \b");
在ReadKey方法之后添加,它可以工作.奇怪的是,当我将应用程序复制到我的桌面时,它不会等待用户输入并自动关闭.
更新2:现在完美运作.谢谢大家回答!
控制台有一个方法,您可以检查是否已重定向stdin.
public static bool IsInputRedirected { get; }
Run Code Online (Sandbox Code Playgroud)
/// <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) { }
}
Run Code Online (Sandbox Code Playgroud)