2014-02-14 74 views
1

我寫在.NET 4小,交互式的控制檯應用程序我想要擴展這是能夠處理任意輸入重定向,以及像:接收用戶輸入後,閱讀管道輸入

echo hello | myapp.exe 

麻煩當然重定向的輸入會竊取「鍵盤流」,所以任何對Console.Read *()的調用都會返回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上這項工作?

謝謝!

[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() 

但這將創建另一個控制檯窗口,我不是很想。相反,我重視使用

AttachConsole(-1) // -1 = "Parent". 

我只能推測,.NET類控制檯保存到以前的標準輸入流的引用父控制檯(現有的cmd.exe),但只有調用Console.SetIn()Console.ReadLine()後回到它的阻擋行爲,等待用戶輸入。

現在就來調查,如果我用我的應用程序的標準輸出重定向運行會發生什麼:

echo hello | myapp.exe | somewhere ... 

回答

1

AttachConsole功能應該做的工作,雖然我只用它來恢復產出而非投入。

+0

結合使用P/Invoke ofFreeConsole()/ AttachConsole()和Console.SetIn()實際上可行,謝謝! (我會更新原始帖子以顯示完整的代碼) – Fredrik