WMI Programming with Visual Basic.NET: Managing the OS, continued - 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 respective service is configured differently). But we can also pause, resume or stop the service manually (based on the user's credentials and type of service). Now the question is, how can you 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 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, you'll see that 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 (assumed), I created an array with only one element (zero yields to single location) and copying the service object to the array (only one gets copied). After that, I assign that array element to “oItem” of type “ManagementObject”, where we can get the state of the service. Consider my apologies, as I could not find a better solution than this method of retrieving a single object from “ManagementObjectCollection”. I would be very glad if anyone could investigate and give me a better solution.
And 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