检测exe何时启动vb.net

时间:2013-09-12 06:55:25

标签: vb.net process

任何人都知道如何让我的VB.net应用程序等到检测到进程正在运行?

我可以找到一个exe运行完毕后如何检测的示例,但没有检测到exe何时启动?

4 个答案:

答案 0 :(得分:4)

您可以使用System.Management.ManagementEventWatcher等待某些WMI事件发生。你需要给它一个查询类型和条件,让它监视你的进程的下一次创建,然后让它在发生时做一些事情。

例如,如果你想:

Dim watcher As ManagementEventWatcher

Public Sub Main()
    Dim monitoredProcess = "Notepad.exe"
    Dim query As WqlEventQuery = New WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa ""Win32_Process"" And TargetInstance.Name = """ & monitoredProcess & """")

    watcher = New ManagementEventWatcher()
    watcher.Query = query

    'This starts watching asynchronously, triggering EventArrived events every time a new event comes in.
    'You can do synchronous watching via the WaitForNextEvent() method
    watcher.Start()

End Sub

Private Sub Watcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles watcher.EventArrived
    'Do stuff with the startup event
End Sub  

最终您需要停止观察者,您可以通过关闭应用或拨打watcher.Stop()来执行此操作。这已被写成脑编译器,所以如果有任何问题请告诉我。

答案 1 :(得分:0)

你可以简单地等待,并且每隔一段时间检查一下这个过程是否存在。使用Thread.Sleep可以避免繁忙等待。

但是,如果您在等待期间启动并存在该过程,则可能会错过该过程。

答案 2 :(得分:0)

您可以使用以下条件

return Process.GetProcesses()。Any(Function(p)p.Name.Contains(myProcessName))

答案 3 :(得分:0)

   Dim p() As Process

 Private Sub CheckIfRunning()
        p = Process.GetProcessesByName("processName")
        If p.Count > 0 Then
            ' Process is running
        Else
            ' Process is not running
        End If
    End Sub

或简单

  

System.Diagnostics.Process.GetProcessesByName("processName")