AllTheTimeWorld.com

csharp booleanTop or bottom?

Top or bottom?

On mouse move determine if the mouse is on top or bottom of form

Top or bottom?

On mouse move determine if the mouse is on top or bottom of form

In a previous lesson, we wrote code to display the X and Y values as we moved the mouse.

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.
In the properties of the form, click the and select the MouseMove event.

Write the code as shown below:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
   //this.Text = "X=" + e.X +" Y="+e.Y;
   if (e.Y < this.Height / 2) this.Text = "Top";
   else this.Text = "Bottom";
 }

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?

This could also be written as shown below:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
   //this.Text = "X=" + e.X +" Y="+e.Y;
   if (e.Y < this.Height / 2)
   {
      this.Text = "Top"; //The mouse position is < half the height of the screen
   }
   else
   {
      this.Text = "Bottom";
   }
}

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