WMI Programming with Visual Basic.NET: Managing the OS, continued - How to modify (manage) the state of a service
(Page 4 of 6 )
This section actually manipulates (manages) the state of the service selected from the listbox. The “Win32_service” class mainly has the following methods to change the state of the service:
- StartService
- StopService
- PauseService
- ResumeService
Of course, there exist a few more too, but we shall concentrate on only the first two methods. The implementations of the last two methods are very similar to those of the first two methods. Recalling from the first section, we need to work with “InvokeMethod” of the class “ManagementObject” and receive the results in the form of an object of type “ManagementBaseObject” class. The following is the code fragment which tries to “stop” the service selected from the listbox:
DimserviceNameAsString=Me.lstServices.SelectedItem.
ToString
DimsearcherAsNewManagementObjectSearcher("SELECT * FROM Win32_service WHERE DisplayName='" & serviceName & "'")
DimoItemsAsManagementObjectCollection = searcher.Get()
Dimar(0)AsObject
oItems.CopyTo(ar, 0)
DimoitemAsManagementObject = ar(0)
' Execute the method
DimoutParamsAsManagementBaseObject = oitem.InvokeMethod("StopService",Nothing,Nothing)
DimobjAsObject= outParams("ReturnValue")
Ifobj.ToString = "0"Then
MessageBox.Show("Succesfully stopped..")
lstServices_SelectedIndexChanged(Nothing,Nothing)
Else
MessageBox.Show("Could not Stop, Returned code:" & obj.ToString)
EndIf
The above fragment stops the service. To start the service, just replace “StopService” in the above program with “StartService” and modify the messages being displayed using “MessageBox.Show” statements. You could see a message box showing “Succesfully stopped” as shown in the following figure (Fig 3).

The next section gives a detailed explanation about the previous code fragment.
Next: How the above program works >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee