WMI Programming with Visual Basic.NET: Combining with Windows Services - Implementing the logic
(Page 3 of 5 )
Add these two statements at the class level (above OnStart method):
DimqueryAsWqlEventQuery
DimwatcherAsManagementEventWatcher
Add the following code within the “OnStart” method
query =NewWqlEventQuery( _
"__InstanceModificationEvent", _
NewTimeSpan(0, 0, 1), _
"TargetInstance isa ""Win32_Service""")
watcher =NewManagementEventWatcher(query)
AddHandlerwatcher.EventArrived,AddressOfHandleEvent
' Start listening
watcher.Start()
EventLog.WriteEntry("WMIService", "Started")
Add the following event handler with the same class:
PublicSubHandleEvent(ByValsenderAsObject,ByValeAsEventArrivedEventArgs)
Try
DimevAsManagementBaseObject = e.NewEvent
DimServiceNameAsString=CType(ev("TargetInstance"), ManagementBaseObject)("DisplayName")
DimStatusAsString=CType(ev("TargetInstance"), ManagementBaseObject)("State")
DimcnAsNewSqlConnection("data source=.;initial catalog=northwind;user id=sa")
cn.Open()
DimcmdAsNewSqlCommand("insert into ServiceHistory(ServiceName,Status) values ('" & ServiceName & "','" & Status & "')", cn)
cmd.ExecuteNonQuery()
cmd.Dispose()
cn.Close()
CatchexAsException
EventLog.WriteEntry("WMIService", ex.Message)
EndTry
EndSub
Add the following lines to the “OnStop” method:
watcher.Stop()
EventLog.WriteEntry("WMIService", "Stopped")
Make sure you change the connection string according to your requirements. Rebuild the solution to ensure that there exist no errors. The project should be built successfully at this moment.
Next: Adding the installers and setup >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee