Mouse Enter & Mouse Leave on a form
I have a form with child controls. I want when user move mouse over the form, the form will be closed. So I catch mouse enter and move leave on the form. But if I move mouse on any controls in form, mouse leave event will be also caught.
Please help me to solve this problem. Thanks.
UPDATE: When the cursor's position is on the form's caption region (this region is called non-client region). I move mouse out of this region, I can't receive the WM_MOUSELEAVE message as well as WM_NCMOUSELEAVE. Please help me in this problem. I want to receive a message when move mo开发者_运维问答use out of this region. Thanks.
Essentially you want to check if the cursor is in the scope of the control. Here is the solution:
(1) Add a Panel
in the form which is the same size as your Form
, and move all controls in the form to the panel. It's easy to change: open MyForm.designer.cs
, add the panel, and change all statements like this.Controls.Add(myLabel);
to this.myPanel.Controls.Add(myLabel);
.
(2) Deal with MouseEnter
and MouseLeave
events of 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
statements in step 2 to an extension method, which is helpful to furthur usage.
this is happening because you have gap between your child Controls on leaving from controls the form_mouseEnter event fires automatically
a way you can do like placing controls with no gap
or
If you don't want user to leave your Control you can set boundary of cursor use this
Cursor.Clip=Control_name.Bounds;
精彩评论