lev*_*l42 2 vb.net timer process monitor
我有以下代码:
Dim p() As Process
Private Sub CheckIfRunning()
p = Process.GetProcessesByName("skype") 'Process name without the .exe
If p.Count > 0 Then
' Process is running
MessageBox.Show("Yes, Skype is running")
Else
' Process is not running
MessageBox.Show("No, Skype isn't running")
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CheckIfRunning()
End Sub
Run Code Online (Sandbox Code Playgroud)
而且效果很好!
但我想知道如何将其转换为监控应用程序,以不断检查进程是否正在运行。是否像每 1 秒检查一次计时器一样简单,还是有更好、更有效的方法来解决这个问题。
最后,我想要一个标签,根据流程显示“正在运行”或“未运行”,但我需要一些东西来不断地观察流程。
如果您需要应用程序一直运行,那么您根本不需要 Timer。订阅Process.Exited()事件以在它关闭时收到通知。例如,使用记事本:
Public Class Form1
Private P As Process
Private FileName As String = "C:\Windows\Notepad.exe"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ps() As Process = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(FileName))
If ps.Length = 0 Then
P = Process.Start(FileName)
P.EnableRaisingEvents = True
AddHandler P.Exited, AddressOf P_Exited
Else
P = ps(0)
P.EnableRaisingEvents = True
AddHandler P.Exited, AddressOf P_Exited
End If
End Sub
Private Sub P_Exited(sender As Object, e As EventArgs)
Console.WriteLine("App Exited @ " & DateTime.Now)
Console.WriteLine("Restarting app: " & FileName)
P = Process.Start(FileName)
P.EnableRaisingEvents = True
AddHandler P.Exited, AddressOf P_Exited
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
这将使其始终保持打开状态,假设您想在它尚未运行时打开它。
如果您不想自己打开它,并且需要检测它何时打开,那么您可以通过ManagementEventWatcher使用 WMI,如上一个 SO question 中所述。