Mouse Enter & Mouse Leave on form

I have a form with child controls. I want the user to move the mouse over the form, the form will be closed. So I catch the mouse and move the vacation in shape. But if I move the mouse to any controls on the form, the mouse abandonment event will also be caught.

Please help me solve this problem. Thanks.

UPDATE: When the cursor position is in the subtitle area of ​​the form (this area is called the non-client area). I move the mouse from this region, I can not get the WM_MOUSELEAVE message, as well as WM_NCMOUSELEAVE. Please help me with this problem. I want to receive a message when you move the mouse from this region. Thanks.

+4
source share
2 answers

Essentially, you want to check if the cursor is in the control area. Here is the solution:

(1) Add a Panel in the form that is the same size as your Form , and move all the controls on the form to the panel. Easy to change: open MyForm.designer.cs , add a panel and change all statements like this.Controls.Add(myLabel); at this.myPanel.Controls.Add(myLabel); .

(2) Handle the MouseEnter and MouseLeave events in the panel you added.

 myPanel.MouseEnter += (sender, e) => { //enter }; myPanel.MouseLeave += (sender, e) => { if (Cursor.Position.X < myPanel.Location.X || Cursor.Position.Y < myPanel.Location.Y || Cursor.Position.X > myPanel.Location.X + myPanel.Width || Cursor.Position.Y > myPanel.Location.Y + myPanel.Height) { //out of scope } }; 

(3) Why not use Form in step 2? Why do we need a Panel with the same size? Try it yourself. The narrow border of the form will make you crazy.

(4) You can make the if in step 2 as an extension method, which is useful for use.

+1
source

this is because you have a gap between your child control when the form_mouseEnter event exits the controls, it fires automatically

the way you can do, for example, placing controls without spaces

or

If you do not want the user to leave your control, you can set the cursor border use this

 Cursor.Clip=Control_name.Bounds; 
0
source

All Articles