Handling Mouse Events in VB.NET

Handling events in VB is little bit tricky than in C++ or C#. In VB.NET, you write a delegate and then write an event handler. These event handlers are overridable public events defined in the Control or other WinForms classes.
  • 2282

Handling events in VB is little bit tricky than in C++ or C#. In VB.NET, you write a delegate and then write an event handler.  These event handlers are overridable public events defined in the Control or other WinForms classes.

  1. Write a Delegate.

    I want to handle Mouse Down events and do something when left or right mouse buttons are pressed. Write this line of code in your InitializeComponent function.

    AddHandler Me.MouseDown AddressOf Me.Form_MouseDown
     
  2. Write the Event.

    Now you write the event handle. The output parameter of your event returns System.WinForms.MouseEventArgs object which gives you the details about mouse down such as what button is pressed or how many times. Here are MouseEventArgs members.

MouseEventArgs members.

Button Indicates which mouse button was pressed. It could be Left, Right, Middle, or None.
Clicks  Indicates the number of times the mouse button was pressed and released.
Delta Indicates a signed count of the number of detents the mouse wheel has rotated.
X The x-coordinate of mouse click.
Y The y-coordinate of mouse click.

Event Handler.

Private Sub Form_MouseDown(sender As Object, e As System.WinForms.MouseEventArgs)
Select Case e.Button
Case MouseButtons.Left
MessageBox.Show(
Me, "Left Button Click")
Case MouseButtons.Right
MessageBox.Show(
Me, "Right Button Click")
Case MouseButtons.Middle
Case Else
End
Select
End
Sub 'Form_MouseDown

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.