MouseHover and MouseLeave Events controlling

前端 未结 4 1697
无人及你
无人及你 2020-12-11 09:18

I was building a simple form with one simple effect- opacity reduced when mouse is not over the form, and form becomes opaque when mouse is over it. I am currently encounter

4条回答
  •  温柔的废话
    2020-12-11 09:33

    The MouseEnter/Leave events are too unreliable to do this. Best thing to do is just use a Timer that checks if the mouse is still inside the window. Drop a Timer on the form and make the code look like this:

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            this.Opacity = 0.99;
            timer1.Interval = 200;
            timer1.Enabled = true;
            timer1.Tick += timer1_Tick;
        }
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            timer1_Tick(this, e);
        }
        private void timer1_Tick(object sender, EventArgs e) {
            this.Opacity = this.Bounds.Contains(this.PointToClient(Cursor.Position)) ? 0.99 : 0.20;
        }
    }
    

    Btw: avoid increasing the Opacity to 1.0, that forces the native window to be recreated and that can have a lot of side-effects. Using 0.99 is best.

提交回复
热议问题