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.
source share