|
Now lets create a Windows form which interfaces with the Printer class. The Windows form has a Status panel which displays the Ink status of the cartridge(Full, Half, Low and Empty) and a Trackbar. We can decrease/increase the level of ink in the cartridge using the Trackbar.
' ** Create an instance of the Printer class
Dim oPrinter As New Printer
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
' ** register the Delegate of CartridgeStatus Method with the Printer class
' Notice that when we pass the Address of the Method along with a new
' instance of the Delegate, New Printer.CartridgeEventHandler
oPrinter.SetDlgRef(New Printer.CartridgeEventHandler(AddressOf _
CartridgeStatus))
oPrinter.Name = "HP DeskJet 640C"
' ** Set the level of ink in the cartridge
oPrinter.InkLevel = 100
' ** set the position of the Trackbar based on the value of the Ink level
Me.trInkLevel.Value = (oPrinter.InkLevel / 100) * trInkLevel.Maximum
End Sub
' ** The Method that will invoked by the Delegate, Notice the Method signature
' is the same as that of the Delegate
' ** The status panel will be updated with values based on the values that was
' passed by the delegate
Private Sub CartridgeStatus(ByVal nCartridgeState As Printer.CartridgeState)
Dim sState As String
Select Case nCartridgeState
Case Printer.CartridgeState.FULL
sState = "FULL"
Case Printer.CartridgeState.HALF
sState = "HALF"
Case Printer.CartridgeState.LOW
sState = "LOW"
Case Printer.CartridgeState.EMPTY
sState = "EMPTY"
End Select
pnCartridgeInk.Text = sState
End Sub
' ** As the Trackbar is scrolled, the InkLevel property of the Printer is also
' updated
Private Sub trInkLevel_Scroll(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles trInkLevel.Scroll
oPrinter.InkLevel = (trInkLevel.Value / trInkLevel.Maximum) * 100
End Sub
Imagine the number of applications you can have with the power of Delegates woven into your programming! To be crystal clear with the usage of Delegates, I suggest you get your hands dirty and try examples on your own and don't delegate it to somebody!
The above example is that of Singlecast Delegates. Now what if you want the Delegate to represent Multiple Methods ...sounds like fun,thats where Multicast Delegates come in. But that is in the next section later on this week. Ciao!
|