In a previous lesson, we wrote code to display the X and Y values as we moved the mouse.
Private Sub Form1_MouseMove(ByVal sender As Object, _
      ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
  Me.Text = e.X & "," & e.Y
End Sub

In this example we will use the X value to determine if the mouse is on the top or bottom half of the form.
Start a new project and save it as Location. Write the code as shown below:

  Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
     If e.Y < Me.Height / 2 Then
         Me.Text = "Top"
     Else
         Me.Text = "Bottom"
     End If
  End Sub 'Form1_MouseMove

Run the program and move the mouse from right to left to see if the information if correct. Resize the form. Does it still work?

Experiment: Modify the code so that it displays either "Left" or "Right".

Next we will modify the code to display "Top Left", "Top Right", "Bottom Left" or "Bottom Right." We will first determine if it is Top or bottom and set the text, then we will concatenate either "left" or "right" to the existing text.

 Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
    If e.Y < Me.Height / 2 Then
        Me.Text = "Top "
    Else
        Me.Text = "Bottom "
    End If
    If e.X < Me.Width / 2 Then
        Me.Text = Me.Text & "left"
    Else
        Me.Text = Me.Text & "right"
    End If
  End Sub 'Form1_MouseMove 
It is much easier to write the code this way, with two separate IF-ELSE blocks than to try to determine if the mouse is on the "top left" in one Boolean expression.
INDEX, IF Statements, Top or bottom?, AND And OR, Left or Right?
Next lesson: Drawing in Visual Basic

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Top or bottom?