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:
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
MouseEnter is triggered when your mouse enters a given control. Meaning if you move your mouse over a control, it will be triggered
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.
Create a Windows Forms app
Add a PictureBox control on it
Assign the following events: pictureBox1.MouseLeave += (sender, e) => { MessageBox.Show(“Mouse left picturebox”); };pictureBox1.MouseEnter += (sender, e) =>{ MessageBox.Show(“Mouse entered picturebox”); };
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!
Image by OpenClipart-Vectors
コメント