1

我在 c# 中使用鼠标悬停单击,但我希望它在单击前等待 2-3 秒,如果光标没有在按钮上停留 2 秒或更长时间,它将不会单击。

4

1 回答 1

2

Button您可以通过从类派生来实现该功能:

using System;
using System.Windows.Forms;

namespace MouseHoverDelay
{
    public class HoverButton : Button
    {
        protected System.Timers.Timer timer;

        public bool IsHoverEnabled { get; set; }
        public double Delay { get; set; }

        public event System.Timers.ElapsedEventHandler TimerElapsed
        {
            add
            {
                timer.Elapsed += value;
            }
            remove
            {
                timer.Elapsed -= value;
            }
        }

        public HoverButton()
        {
            // defaults: hover trigger enabled with 3000 ms delay
            IsHoverEnabled = true;
            Delay = 3000;

            timer = new System.Timers.Timer
            {
                AutoReset = false,
                Interval = Delay
            };
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);

            if (IsHoverEnabled)
            {
                timer.Start();
            }
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);

            timer.Stop();
        }
    }
}

将其添加到表单后,您需要在表单Delay的方法中设置它和处理程序方法InitializeComponent()

this.btnHoverTest.Delay = 2000;
this.btnHoverTest.TimerElapsed += timer_Elapsed;

然后以如下形式实现处理程序:

using System;
using System.Windows.Forms;

namespace MouseHoverDelay
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // triggers when Delay milliseconds have passed since hovering mouse over control
        protected void timer_Elapsed(object o, EventArgs e)
        {
            MessageBox.Show("Hovered for 2 seconds!");
        }
    }
}
于 2012-06-05T15:34:33.337 回答