简体   繁体   English

检测exe何时启动vb.net

[英]Detect when exe is started vb.net

Dose anybody know how I can make my VB.net application wait until a process is detected as running? 有人知道我如何让我的VB.net应用程序等待直到检测到进程正在运行吗?

I can find example of how to detect once an exe has finished running but none that detect when an exe is started? 我可以找到一个示例,该示例如何检测一个exe文件是否已运行完毕,但是没有一个可以检测到何时启动exe文件?

You can use the System.Management.ManagementEventWatcher to wait for certain WMI events to occur. 您可以使用System.Management.ManagementEventWatcher等待某些WMI事件发生。 You need to give it a query type and condition to have it watch for the next creation of your process, then get it to do something when that occurs. 您需要给它一个查询类型和条件,以使其监视下一次创建的流程,然后让它在发生这种情况时执行某些操作。

For example, if you want : 例如,如果您想要:

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  

Eventually you'll need to stop the watcher, which is you can do by closing the app, or calling watcher.Stop() . 最终,您需要停止监视程序,这可以通过关闭应用程序或调用watcher.Stop() This has been written as brain compiler, so if there's any issues let me know. 这已被编写为大脑编译器,所以如果有任何问题请告诉我。

You could simply wait and check every once in a while whether the process exists. 您可以稍等片刻,然后每隔一段时间检查一次该过程是否存在。 Use Thread.Sleep to avoid busy waiting. 使用Thread.Sleep可以避免繁忙的等待。

However, this has the possibility that you miss the process if it starts and exists during your wait time. 但是,这有可能使您错过该过程,如果该过程开始并且在您的等待时间内存在。

You can use the below condition 您可以使用以下条件

return Process.GetProcesses().Any(Function(p) p.Name.Contains(myProcessName)) 返回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

OR SIMPLY 或简单地

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM