WMI Programming with Visual Basic.NET: Breaking the Ice - Our first program to connect to WMI (on a local computer)
(Page 2 of 4 )
I just gave you a huge amount of theory without any practical examples. Now we shall create a simple windows application using Visual Basic.NET to get some information from WMI. Let's start by opening Visual Studio.NET 2003 Enterprise Architect.
- After opening Visual Studio.NET 2003 IDE, go to File menu -> new -> Project.
Within the Visual Basic projects, select the "Windows Application" template (as shown in Fig. 1 below) and provide the name as "WMISample" at your own location and finally click OK.
Figure 1- Drag a button and a listbox from the toolbox onto the form.
- Name them as "btnShowDrives" and "lstDrives" respectively. The form should look like the one in Fig. 2 below.

Figure 2
- Go to Project menu -> Add Reference. Choose System.Management in the list of components (of .NET tab) and pressthe "select" button. Finally click OK. You should be able to see System.Management as part of "references" in the solution explorer.
- Modify your code so that it looks like the following:
Imports System
Imports System.Management
Public Class Form1
Inherits System.Windows.Forms.Form
.
.
.
Private Sub btnShowDrives_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowDrives.Click
'connect to "Win32_LogicalDisk" class of WMI
Dim diskClass As New ManagementClass("Win32_LogicalDisk")
'get the information
Dim disks As ManagementObjectCollection = diskClass.GetInstances()
'loop the information to store in an array
Dim disk As ManagementObject
Dim arDisks As New ArrayList
For Each disk In disks
arDisks.Add(disk("deviceid").ToString())
Next disk
'populate the listbox
Me.lstDrives.Items.AddRange(arDisks.ToArray)
End Sub
End Class
Now, press F5 to execute the program. Click on the "Show Drives" button. And you should be able to see the listbox filled with all the drives attached (logically) to your computer (as in Fig.3).

Figure 3
Don't ignore the next section. It not only explains the above program, but also gives you a few tips on some interesting aspects.
Next: Getting information from WMI >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee