C#WPF读取控制台输出

时间:2016-04-06 19:45:29

标签: c# wpf

我正在编写一个显示您在以太坊中的当前哈希值的应用程序(像比特币这样的加密货币),我需要以某种方式从正在运行的命令行获取连续输出。这是我到目前为止,但它不打印到程序输出:

 pProcess.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
    // Prepend line numbers to each line of the output.
    if (!String.IsNullOrEmpty(e.Data))
    {
        System.Console.Write(e.Data);
    }
});

//Wait for process to finish
pProcess.WaitForExit();

什么不能使用此代码?我猜测事件处理程序搞砸了,但我不知道是什么。

1 个答案:

答案 0 :(得分:1)

将其复制并粘贴到我为您修改的代码中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

    namespace ETHMinerVisualiser
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }

            private void MineButton_Click(object sender, RoutedEventArgs e)
            {
                Task.Run(() => { startMining(); });
            }

            public void startMining()
            {
                //Create process
                System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

                //strCommand is path and file name of command to run
                pProcess.StartInfo.FileName = @"E:/Documents/ETH/ETHMinerVisualiser/ethminer-cuda-0.9.41-new/ethminer.exe";

                //strCommandParameters are parameters to pass to program
                pProcess.StartInfo.Arguments = "-F eu1.ethermine.org:5555/0x9c3f6281b123541f10c9bf37a8f273aa2a774d17.PCGPU -C";

                pProcess.StartInfo.UseShellExecute = false;


                //Set output of program to be written to process output stream
                pProcess.StartInfo.RedirectStandardOutput = true;

                //Optional
                pProcess.StartInfo.WorkingDirectory = "";

                //Start the process
                pProcess.Start();

                //pProcess.StartInfo.CreateNoWindow = true;

                //pProcess.BeginOutputReadLine();

                pProcess.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    // Prepend line numbers to each line of the output.
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        //System.Console.Write(e.Data);                   
                        Debug.WriteLine(e.Data);
                    }
                });

                //Wait for process to finish
                pProcess.BeginOutputReadLine();

                pProcess.WaitForExit();
            }
        }
    }