Boolean Expressions in Visual Basic

In a previous lesson, we wrote code to display the X and Y values as we moved the mouse.
'Programmer: Janet Joy
'Show x,y position when mouse moves
Public Class Form1
    Private Sub moving(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        Me.Text = e.X & "," & e.Y
    End Sub
End Class

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:

'Programmer: Janet Joy
'Tell if y position is top or bottom when mouse moves
Public Class Form1
    Private Sub moving(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        If e.Y < Me.Height / 2 Then
            Me.Text = "Top"
        Else
            Me.Text = "Bottom"
        End If
    End Sub
End Class

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.

'Programmer: Janet Joy
'Tell if position is top or bottom and left or right when mouse moves
Public Class Form1
    Private Sub moving(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        Dim position As String
        If e.Y < Me.Height / 2 Then
            position = "Top "
        Else
            position = "Bottom "
        End If
        If e.X < Me.Width / 2 Then
            position = position & "left"
        Else
            position = position & "right"
        End If
        Me.Text = position
    End Sub
End Class
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.

NEXT: AND And OR