ac# winforms プログラムがコンソール ウィンドウに書き込む方法はありますか?
1 に答える
ここでは基本的に 2 つのことが起こります。
- コンソール出力
winforms プログラムは、それを作成したコンソール ウィンドウ (または別のコンソール ウィンドウ、または必要に応じて新しいコンソール ウィンドウ) に自分自身をアタッチすることができます。コンソール ウィンドウ Console.WriteLine() などに接続すると、期待どおりに動作します。このアプローチの落とし穴の 1 つは、プログラムがすぐにコンソール ウィンドウに制御を返し、その後、コンソール ウィンドウへの書き込みを続行することです。これにより、ユーザーはコンソール ウィンドウに入力することもできます。/wait パラメータを指定して start を使用すると、これを処理できると思います。
- リダイレクトされたコンソール出力
これは、誰かがあなたのプログラムからの出力を別の場所にパイプするときです。
あなたのアプリ > file.txt
この場合、コンソール ウィンドウにアタッチすると、実質的に配管が無視されます。これを機能させるには、Console.OpenStandardOutput() を呼び出して、出力がパイプされるストリームへのハンドルを取得します。これは、出力がパイプされている場合にのみ機能するため、両方のシナリオを処理する場合は、標準出力を開いて書き込み、コンソール ウィンドウにアタッチする必要があります。これは、出力がコンソール ウィンドウとパイプに送信されることを意味しますが、これが私が見つけた最善の解決策です。これを行うために使用するコードの下。
// This always writes to the parent console window and also to a redirected stdout if there is one.
// It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise
// write to the console) but it doesn't seem possible.
public class GUIConsoleWriter : IConsoleWriter
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
StreamWriter _stdOutWriter;
// this must be called early in the program
public GUIConsoleWriter()
{
// this needs to happen before attachconsole.
// If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere
// I guess it probably does write somewhere, but nowhere I can find out about
var stdout = Console.OpenStandardOutput();
_stdOutWriter = new StreamWriter(stdout);
_stdOutWriter.AutoFlush = true;
AttachConsole(ATTACH_PARENT_PROCESS);
}
public void WriteLine(string line)
{
_stdOutWriter.WriteLine(line);
Console.WriteLine(line);
}
}