读取管道输入后接收用户输入 [英] Receiving user input after reading piped input
问题描述
我正在.NET 4中编写一个小型的交互式控制台应用程序。我想扩展它以便能够处理可选的重定向输入,例如:
I am writing a small, interactive console application in .NET 4. I want to extend this to be able to handle optional redirected input as well, like:
echo hello | myapp.exe
麻烦当然是重定向的输入窃取了键盘流,所以任何调用到Console.Read *()返回null。
Trouble is of course that the redirected input steals the "keyboard stream", so any calls to Console.Read*() returns null.
目前我所拥有的是:
// Read piped input
try
{
bool keyAvailable = Console.KeyAvailable;
}
catch
{
string redirected = Console.In.ReadToEnd();
// Need to do something here to "un-redirect" stdin back to keyboard
}
// Always returns null
String userInput = Console.ReadLine();
在UNIX上我可以打开一个到/ dev / tty的流来获取用户输入,但我怎么能在Windows上使这个工作?
On UNIX I could open a stream to /dev/tty to get user input, but how can I make this work on Windows?
谢谢!
基于Craig答案的工作解决方案:
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern bool FreeConsole();
try
{
bool keyAvailable = Console.KeyAvailable;
}
catch
{
string redirectedInput = Console.In.ReadToEnd();
bool freed = FreeConsole();
bool attached = AttachConsole(-1);
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
}
我必须首先使用
FreeConsole().
我可以选择使用
AllocConsole()
但这会产生另一个控制台窗口,我真的不想要。相反,我使用
but that would create another console window, which I don't really want. Instead I attach to the parent console (the existing cmd.exe) using
AttachConsole(-1) // -1 = "Parent".
我只能推测.NET类控制台保存对前一个stdin流的引用,但仅限于在调用 Console.SetIn()
后, Console.ReadLine()
回到它的阻塞行为,等待用户输入。
I can only speculate that the .NET class Console holds a reference to the previous stdin stream, but only after the call to Console.SetIn()
the Console.ReadLine()
is back to it's blocking behavior, waiting for user input.
现在开始调查如果我运行我的应用程序的stdout重定向会发生什么:
Now on to investigate what happens if I run with my application's stdout redirected:
echo hello | myapp.exe | somewhere ...
推荐答案
AttachConsole 功能应该可以完成这项工作,不过我只用它来重新获得输出而不是输入。
The AttachConsole function should do the job, though I've only used it to regain output rather than input.
这篇关于读取管道输入后接收用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!