How to detect when the mouse leaves the form?

前端 未结 4 766
南笙
南笙 2020-12-11 21:23

I have a form with a lot of controls on it. How can I detect when the mouse leaves the form? I\'ve tried wiring up a MouseLeave event for every single control and the form

4条回答
  •  悲哀的现实
    2020-12-11 22:21

    The only reliable way I know of is a timer. Here's sample code that tweaks the opacity on a roll-over:

      public partial class Form1 : Form {
        Timer timer1 = new Timer();
        public Form1() {
          InitializeComponent();
          this.Opacity = 0.10;
          timer1.Tick += new EventHandler(timer1_Tick);
          timer1.Interval = 200;
          timer1.Enabled = true;
        }
    
        void timer1_Tick(object sender, EventArgs e) {
          Point pos = Control.MousePosition;
          bool inForm = pos.X >= Left && pos.Y >= Top && pos.X < Right && pos.Y < Bottom;
          this.Opacity = inForm ? 0.99 : 0.10;
        }
      }
    

提交回复
热议问题