Handling Mouse Events in Forms
We can handle mouse events such as mouse pointer movements in Forms. The mouse events supported by VB .NET are as follows:
MouseDown: This event happens when the mouse pointer is over the form/control and is pressed
MouseEnter: This event happens when the mouse pointer enters the form/control
MouseUp: This event happens when the mouse pointer is over the form/control and the mouse button is released
MouseLeave: This event happens when the mouse pointer leaves the form/control
MouseMove: This event happens when the mouse pointer is moved over the form/control
MouseWheel: This event happens when the mouse wheel moves while the form/control has focus
MouseHover: This event happens when the mouse pointer hovers over the form/control
The properties of the MouseEventArgs objects that can be passed to the mouse event handler are as follows:
Button: Specifies that the mouse button was pressed
Clicks: Specifies number of times the mouse button is pressed and released
X: The X-coordinate of the mouse click
Y: The Y-coordinate of the mouse click
Delta: Specifies a count of the number of detents (rotation of mouse wheel) the mouse wheel has rotated
Working with an Example
We will work with an example to check the mouse events in a form. We will be working with MouseDown, MouseEnter and MouseLeave events in this example. Drag three TextBoxes (TextBox1, TextBox2, TextBox3) onto the form. The idea here is to display the results of these events in the TextBoxes.
Code
Public Class Form1 Inherits System.Windows.Forms.Form 'Windows Form Designer Generated Code Private Sub Form1_Mousedown(ByVal sender As System.Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown If e.Button = MouseButtons.Left Then TextBox1.Text = "Mouse down at" + CStr(e.X) + " :" + CStr(e.Y) 'displaying the coordinates in TextBox1 when the mouse is pressed on the form End If End Sub Private Sub Form1_MouseEnter(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles MyBase.MouseEnter TextBox2.Text = "Mouse Entered" 'displaying "mouse entered" in TextBox2 when the mouse pointer enters the form End Sub Private Sub Form1_MouseLeave(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles MyBase.MouseLeave TextBox3.Text = "Mouse Exited" 'displaying "mouse exited" in Textbox3 when the mouse pointer leaves the form End Sub End Class |
The image below displays the output.
Beep Function
The Beep Function in VB.NET can be used to make the computer emit a beep. To see how this works, drag a Button onto the form and place the following code in it's click event:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click Beep() End Sub |
When you run the code and click the button your computer emits a beep.
No comments:
Post a Comment