有人知道如何让我的 VB.net 应用程序等到检测到进程正在运行吗?
我可以找到有关如何检测 exe 完成运行但没有检测到 exe 何时启动的示例?
您可以使用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()
. 这是作为大脑编译器编写的,所以如果有任何问题,请告诉我。
您可以使用以下条件
返回 Process.GetProcesses().Any(Function(p) p.Name.Contains(myProcessName))
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")
您可以简单地等待并每隔一段时间检查一下该进程是否存在。用于Thread.Sleep
避免忙于等待。
但是,如果它在您的等待时间内启动并存在,您可能会错过该过程。