Windowsアプリケーションでコンソールアプリケーションを起動し、コマンドラインを読み取る(監視する)方法-C#でリアルタイムに1行ずつ

ラズロボズサー

行を1行ずつ生成するコンソールアプリケーションがあります:Data1 Data2 Data3 ...そしてそのoverコマンドラインがクリアされると、無限に繰り返されます(データは変更される可能性があります)Windowsアプリケーションでコンソールアプリケーションのコマンドラインを監視する必要があります行データの時間と作業(たとえば、行ごとにoxをリストするために保存します)!可能です?

ティモ・サロマキ

基本的に、各行をコンソールに出力できるようにするには、そのコンソールアプリケーションの出力ストリームをサブスクライブする必要があります。

あなたがする必要があるのは、Windowsフォームアプリケーションを作成し(WPFも機能します)、そこからコンソールアプリケーションを起動することです。

現在のコンソールアプリケーションを表示ウィンドウとして表示したくない場合は、CreateNoWindowをtrueに設定することを忘れないでください。

コンソールアプリケーションを起動する方法は次のとおりです。

var processStartInfo = new ProcessStartInfo(fileName, arguments);
processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;
processStartInfo.RedirectStandardOutput = true; // We handle the output
processStartInfo.CreateNoWindow = true; // If you want to hide the console application so it only works in the background.

// Create the actual process
currentProcess = new Process();
currentProcess.EnableRaisingEvents = true;
currentProcess.StartInfo = processStartInfo;

// Start the process
bool processDidStart = currentProcess.Start();

コンソールアプリケーションからの出力をバックグラウンドで読み取るには、BackgroundWorkerが必要です。

outputReader = TextReader.Synchronized(currentProcess.StandardOutput);
outputWorker.RunWorkerAsync();

これで、コンソールアプリケーションからすべての出力をリアルタイムで取得し、それを使用してリストなどを作成できます。

void outputWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Work until cancelled
    while (outputWorker.CancellationPending == false)
    {
        int count = 0;
        char[] buffer = new char[1024];
        do
        {
            StringBuilder builder = new StringBuilder();

            // Read the data from the buffer and append to the StringBuilder
            count = outputReader.Read(buffer, 0, 1024);
            builder.Append(buffer, 0, count);

            outputWorker.ReportProgress(0, new OutputEvent() { Output = builder.ToString() });
        } while (count > 0);
    }
}

処理されたデータは、BackgroundWorkerのProgressChangedイベントを通じて利用できます。

void outputWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (e.UserState is OutputEvent)
    {
        var outputEvent = e.UserState as OutputEvent;

        /* HERE YOU CAN USE THE OUTPUT LIKE THIS:
         * outputEvent.Output
         *
         * FOR EXAMPLE:
         * yourList.Add(outputEvent.Output);
         */
    }
}

上記のコードは、将来存在しなくなった場合に備えて、次のCodeproject.comの記事から目的に合わせて変更されています。C#アプリケーションへのコンソールの埋め込み

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ