WMI Programming with Visual Basic.NET: Trapping System Events - Creating a simple application
(Page 2 of 4 )
Instead of talking too much, let us do it practically. I would like to develop a simple Windows application, which starts to listen for only a single event. Once it receives the notification of a specified event instance, it just displays the status (or information) of that event and stops listening for that event any more. We start with this simple concept, and later develop complicated applications.
So, let us start by opening the Visual Studio.NET 2003 Enterprise Architect. Create a Windows application with only a single button and a multi-lined textbox. Don’t forget to add the reference to “System.Management” (as explained in part one) and import it into your application. Your design should look something like the following figure (Fig 1):

Copy the following code into the button click event:
Me.Button1.Enabled =False
DimqueryAsNewWqlEventQuery( _
"__InstanceModificationEvent", _
NewTimeSpan(0, 0, 1), _
"TargetInstance isa ""Win32_Service""")
DimwatcherAsNewManagementEventWatcher(query)
DimevAsManagementBaseObject = watcher.WaitForNextEvent()
Me.TextBox1.Text &= ControlChars.NewLine & _
"Service’" &CType(ev("TargetInstance"), ManagementBaseObject)("DisplayName") & "’has changed, State is’" &CType(ev("TargetInstance"), ManagementBaseObject)("State") & "’"
watcher.Stop()
Don’t try to understand the above code yet. Just execute it first. Press the button after you have executed your application. It starts listening for the event. To notify the listener, open “services.msc” from Start->Run and change any status of any process (choose a generic process rather than harmful system process like RPC). I generally use “Indexing Service” for demonstration purposes, and I suggest you do the same (unless it is not installed on your computer). When you change the status, you should be able to see the textbox updated accordingly as shown in the following figure (fig 2).

The listener stops listening once it receives the notification of event.
You can obtain the above code from the “form1.vb” file in the zip included for download. The coming sections give you a complete, detailed explanation of the above program.
Next: What is “WqlEventQuery”? >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee