如何知道流程退出事件中的流程名称

时间:2013-09-15 20:01:31

标签: vb.net

我使用Process.start()运行具有不同名称的多个exe,并启用Raisingevents为True。为了检查Process的状态,我在Process Exited事件中暗示了User并向用户显示了一条消息。

但问题是我想在该Exit事件中向用户显示特定的Exe Name。我的For process Start代码是:

Private Sub StartExe()
Private psi As ProcessStartInfo
Private cmd As Process
Dim filePath As String = "vision.exe"
psi = New ProcessStartInfo(filePath)
Dim systemencoding As System.Text.Encoding = _
        System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
    With psi
        .Arguments = "Some Input String"
        .UseShellExecute = False   
        .RedirectStandardError = True
        .RedirectStandardOutput = True
        .RedirectStandardInput = True
        .CreateNoWindow = False
        .StandardOutputEncoding = systemencoding  
        .StandardErrorEncoding = systemencoding
    End With
    cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
    AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
    AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
    AddHandler cmd.Exited, AddressOf processExited
    cmd.Start()
    cmd.BeginOutputReadLine()
    cmd.BeginErrorReadLine()
  End Sub
  'For Receiving the Output of Exe, I used a TextBox to view
   Private Sub Async_Data_Received(ByVal sender As Object, ByVal e As   DataReceivedEventArgs)
  Me.Invoke(New InvokeWithString(AddressOf Sync_Output1), e.Data)
  End Sub
   Private Sub Sync_Output1(ByVal text As String)
    txtLog.AppendText(text & Environment.NewLine)
  End Sub
 'At the Exit event, I inform the user that an Exe exited due to some reason etc.
  Private Sub processExited(ByVal sender As Object, ByVal e As EventArgs)
     Me.BeginInvoke(New Action(Function()
     MessageBox.Show("The Stream for " &Particular Exe&   "is Exited.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

     End Function))
     End Sub

在Process Exited Event中,如何显示触发该事件的特定Exe的名称。就像在那个特定的代码中,我启动了一个“vision.exe”,所以我想通知用户由于某些原因等终止了vision.exe。

1 个答案:

答案 0 :(得分:1)

当Exited事件运行时,该进程已经死亡,您无法再检索其属性。由于您已经使用了lambda表达式,因此您也可以通过编写一个捕获 filePath 变量的表达式来解决这个问题。像这样:

    AddHandler cmd.Exited,
        Sub(s, e)
            Me.BeginInvoke(New Action(
                Sub()
                    MessageBox.Show(filePath + " has ended")
                End Sub))
        End Sub

请注意,在进程终止或您自己的程序退出之前,您必须保持Form对象的活动状态。如果不这样,那么将在已处置的表单上进行BeginInvoke()调用,这也是原始代码中的问题。您可以通过选中Me.InvokeRequired来避免这种情况。如果它返回false,则不要做任何事情。