top of page
Search

The Mouse Events Mysteries: MouseEnter vs MouseHover vs MouseMove vs MouseLeave

There are several events which are available in .NET which might seem a bit confusing at first.

Let’s take an example. You might want to have an event to trigger (e.g. show a menu) when your mouse cursor is over a specific object (e.g. menu button). Which event do you use: MouseHover, MouseEnter, MouseMove?

It really depends on what you want to achieve:

  1. MouseHover is triggered when your mouse pointer rests for a while on the control. Meaning if you constantly move your mouse over a certain control, the event will not be triggered. You need to rest your cursor on it for a while

  2. MouseEnter is triggered when your mouse enters a given control. Meaning if you move your mouse over a control, it will be triggered

  3. MouseMove is triggered when your mouse is moved over a control. It will trigger multiple events as long as your mouse is over that specific control.

Then, you have the complementary event, MouseLeave which is triggered when the mouse leaves the control.

Feel free to check the documentation to ensure our understanding is correct.

So far so good. Then we have this little experiment.

  1. Create a Windows Forms app

  2. Add a PictureBox control on it

  3. Assign the following events: pictureBox1.MouseLeave += (sender, e) => { MessageBox.Show(“Mouse left picturebox”); };pictureBox1.MouseEnter += (sender, e) =>{ MessageBox.Show(“Mouse entered picturebox”); };

  4. Run it!

You will notice that the events don’t appear to be behaving as expected. Why does this happen?

Detectives, your answers are expected in the comments!


コメント


bottom of page