我启动了一个流程并希望获得流程输出以便在我的表单(winform)上显示它,所以我创建了 ProgressChanged 事件。我的问题是由于某种原因我无法进入我的 progressChanged 函数。
我的代码:
BackgroundWorker bgWorker = null;
string pcapFilePathSniffer = "";
这是我开始这个过程的课程:
public class Tshark
{
public int _interfaceNumber;
public string _pcapPath;
Process _tsharkProcess;
public int _packetsCount;
public string _packet;
public string _tsharkPath = @"C:\Program Files\Wireshark\tshark.exe";
public delegate void dlgPackProgress(int progress);
public event dlgPackProgress evePacketProgress;
public Tshark(int interfaceNumber, string pcapPath)
{
_interfaceNumber = interfaceNumber;
_pcapPath = pcapPath;
}
public void startTheCapture()
{
try
{
List<string> list = new List<string>();
_tsharkProcess = new Process();
_tsharkProcess.StartInfo.FileName = @"C:\Program Files\Wireshark\tshark.exe";
//_tsharkProcess.StartInfo.Arguments = string.Format(" -i " + _interfaceNumber + " -c " + int.MaxValue + " -w " + _pcapPath);
_tsharkProcess.StartInfo.Arguments = string.Format("-i " + 2);
_tsharkProcess.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
_tsharkProcess.StartInfo.RedirectStandardOutput = true;
_tsharkProcess.StartInfo.UseShellExecute = false;
_tsharkProcess.StartInfo.CreateNoWindow = true;
_tsharkProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_tsharkProcess.Start();
StreamReader myStreamReader = _tsharkProcess.StandardOutput;
while (!myStreamReader.EndOfStream)
{
evePacketProgress(_packetsCount);
_packet = myStreamReader.ReadLine();
list.Add(_packet);
_packetsCount++;
private void OnPacketProgress(int packet)
{
var handler = evePacketProgress;
if (handler != null)
{
handler(packet);
}
}
}
_tsharkProcess.WaitForExit();
}
catch (Exception e)
{
}
}
}
开始处理的开始按钮:
private void btnStartCapture_Click(object sender, EventArgs e)
{
bgWorker = new BackgroundWorker();
bgWorker.WorkerReportsProgress = true;
bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWSniffer_ProgressChanged);
bgWorker.DoWork += new DoWorkEventHandler(
(s3, e3) =>
{
tshark = new Tshark(2, pcapFilePathSniffer);
tshark.startTheCapture();
tshark.evePacketProgress += new Tshark.dlgPackProgress(
(packet) =>
{
bgWorker.ReportProgress(packet, tshark);
});
});
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
});
bgWorker.RunWorkerAsync();
}
ProgressChanged 函数:
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tshark = e.UserState as Tshark;
listBoxPacketsSnifferTab.Text += tshark._packet;
lblPacketsReceived2.Text = tshark._packetsCount.ToString("#,##0");
}