因此,我的工作中有一个应用程序可以将多个 Windows 服务安装到服务器上。作为一个附带项目,我被要求制作一个简单的 GUI,在每个服务的名称旁边用“灯”(带有红色或绿色点的图片框)列出这些服务。这个想法是,如果这些服务停止运行,“灯”将从绿色变为红色。
我已经构建了 GUI 部分,我可以查询远程服务器的服务,然后将其与我感兴趣的数组进行比较,并根据服务状态将每个服务旁边的“灯”设置为绿色/红色。我挂断的部分是如何实时监控这些服务?目前,我在 Form_Load 事件中只有以下代码:
Dim myConnectionOptions As New System.Management.ConnectionOptions
With myConnectionOptions
.Impersonation = System.Management.ImpersonationLevel.Impersonate
.Authentication = System.Management.AuthenticationLevel.Packet
End With
Try
Dim myManagementScope As System.Management.ManagementScope
myManagementScope = New System.Management.ManagementScope("\\" & SERVERNAME & "\root\cimv2", myConnectionOptions)
myManagementScope.Connect()
Dim query As New Management.ObjectQuery("SELECT * FROM Win32_Service")
Dim searcher As New Management.ManagementObjectSearcher(myManagementScope, query)
Dim i As Integer = 0
For Each queryObj As Management.ManagementObject In searcher.Get()
For Each service As String In arrServices
If queryObj("DisplayName").Equals(service) Then
If queryObj("State").Equals("Stopped") Then
arrLights(i).Image = My.Resources.redlight
End If
i += 1
End If
Next
Next
Catch err As Management.ManagementException
MessageBox.Show("WMI query failed with the following error: " & err.Message)
Catch unauthorizedErr As System.UnauthorizedAccessException
MessageBox.Show("Authentication error: " & unauthorizedErr.Message)
End Try
重复执行此代码的简单计时器会是最好的方法,还是有更优雅的解决方案?我在 VB.NET 和 WMI 方面有一点经验,但在任何类型的实时监控活动中都没有这样的经验。