Winform - determine if mouse has left user control

不羁岁月 提交于 2019-11-27 16:15:45

Hooking all the controls MouseEnter and MouseLeave events, then figuring out if it is still inside the form is pretty painful. A simple timer can get the job done too:

  public partial class Form1 : Form {
    private Timer mTimer;
    public Form1() {
      InitializeComponent();
      mTimer = new Timer();
      mTimer.Interval = 200;
      mTimer.Tick += mTimer_Tick;
      mTimer.Enabled = true;
    }
    private void mTimer_Tick(object sender, EventArgs e) {
      if (!this.DesktopBounds.Contains(Cursor.Position)) this.Close();
    }
  }

Idea 1) When the MouseLeave event fires, you can check the mouse coordinates (relative to screen) and check if they're still within the bounds of your usercontrol. If they are, it should be assumed that the mouse has to pass back through the control to get outside the bounds, and you can safely ignore the event this time.

Idea 2) Attach MouseEnter event handlers to the child controls. Then when the mouse enters one, you will know and can ignore the usercontrol's MouseLeave event. Then when the child's MouseLeave event fires, check for the usercontrol's MouseEnter again.

I think I would add an event handler for MouseLeave for every control that you have and use the Parent property to find the User Control you are after. I agree, it will be a bit painful though.

You can also loop through all the child controls (recursive) on your control, and attach a MouseEnter and MouseLeave event to them as well.

You have to do some bookkeeping if the mouse is in your control, or some child control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!