WMI Programming with Visual Basic.NET: Managing the OS - How to know the state of a service
(Page 3 of 6 )
Every service generally starts when the OS starts and stops automatically when the OS shuts down, unless the service is configured differently. But we can also pause, resume or stop the service manually, based on the user credentials and type of service. Now the question is how to know the state of a service, whether running or stopped or paused or resumed or what?
There exists a property called “state” within the “Win32_Service” class. This actually holds the current state of the service object selected. The following code fragment show you how to fetch that property:
Me.lblState.Text = ""
Me.lblState.Refresh()
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)
Me.lblState.Text = oitem("State")
The first two lines will actually clear the previous message. If you carefully observe the above program, I used the SELECT statement of WQL (explained in part two of my series) along with a WHERE clause based on the service name selected within the listbox. So, it is confirmed that we will get only one object of “Win32_service,” unless more services exist with the same name.
Since there exists only one service with that name, I created an array with only one element (zero yields to single location) and copied the service object to the array; only one gets copied. After that, I am assigning that array element to “oItem” of type “ManagementObject”, where we can get the state of the service. Accept my apologies, as I could not discover a better solution than using this method of retrieving only a single object from “ManagementObjectCollection”. I would be very glad if anyone could investigate and give me a better solution.
Finally, I am assigning the current status of “state” to the label. The following figure (Fig 2) shows you the status of “Indexing Service,” at the bottom of the window, selected within the listbox (on my system).

Next: How to modify (manage) the state of a service >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee