Posted by: Zeeshan Amjad | September 12, 2009

Event Handling in WPF using VB.Net


UIElement class introduced the routing event handling and introduced lots of core events. Here is a simple program to show the usages of Event handling of UIElement class.

  1: Imports System.Windows
  2: Imports System.Windows.Media
  3: Imports System.Windows.Input
  4: 
  5: Public Class MyUIElement
  6:     Inherits UIElement
  7: 
  8:     Protected Overrides Sub OnRender(ByVal drawingContext As System.Windows.Media.DrawingContext)
  9:         MyBase.OnRender(drawingContext)
 10:         Dim rect As Rect
 11:         rect = New Rect(New Point(10, 10), New Point(370, 250))
 12:         Dim gBrush As LinearGradientBrush
 13:         gBrush = New LinearGradientBrush(Colors.AliceBlue, Colors.Blue, _
 14:                                          New Point(0, 0), New Point(1, 1))
 15:         drawingContext.DrawRoundedRectangle(gBrush, New Pen(Brushes.Brown, 5), rect, 10, 10)
 16:     End Sub
 17: End Class
 18: 
 19: Public Class MyWindow
 20:     Inherits Window
 21: 
 22: 
 23:     Public Sub New()
 24:         Title = "MyUIElement Class"
 25:         Width = 400
 26:         Height = 300
 27:         WindowStartupLocation = Windows.WindowStartupLocation.CenterScreen
 28: 
 29:         Content = New MyUIElement()
 30: 
 31:         AddHandler MouseLeftButtonDown, AddressOf OnMouseLeftButtonDownHandler
 32:     End Sub
 33: 
 34:     Public Shared Sub OnMouseLeftButtonDownHandler(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
 35: 
 36:         Dim win As Window
 37:         win = CType(sender, Window)
 38: 
 39:         Dim str As String
 40:         str = String.Format("Click at ({0}, {1})", _
 41:                             e.GetPosition(win).X, _
 42:                             e.GetPosition(win).Y)
 43: 
 44:         MessageBox.Show(str, "MYUIElement", MessageBoxButton.OK, MessageBoxImage.Information)
 45:     End Sub
 46: End Class
 47: 
 48: Public Class wpf19
 49:     Public Shared Sub Main()
 50: 
 51:         Dim win As MyWindow
 52:         win = New MyWindow()
 53: 
 54:         Dim app As Application
 55:         app = New Application()
 56:         app.Run(win)
 57:     End Sub
 58: End Class
 59: 

The output of this program is one rounded rectangle. When user click on the window then it will display a message box with the point where user clicks on the window. Here is an output of this program. Here is the output of this program.

vcwpf_21

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: