如何延迟鼠标悬停时间



我正在C#中制作一个应用程序。每当我将光标悬停在按钮上时,都应该显示消息。此外,如果我再次悬停约3秒,则应在按钮上显示"您的鼠标已悬停3秒"的消息。

试着用这个来解决问题:

private void label1_MouseHover(object sender, EventArgs e)
{
    label_Click(null, null); // this will fire click event
}

您必须设置计时器并使用MouseEnter/MouseLeave事件,如下所示:

    Timer t;
    public MainWindow()
    {
        InitializeComponent();
        t = new Timer(3000);
        t.Elapsed += t_Elapsed;

    }
    void t_Elapsed(object sender, ElapsedEventArgs e)
    {
        MessageBox.Show("Your mouse has been hovering for 3 seconds");
    }

    private void btn_MouseEnter(object sender, MouseEventArgs e)
    {
        //MessageBox.Show("Hovered");
        t.Start();
    }
    private void btn_MouseLeave(object sender, MouseEventArgs e)
    {
        t.Stop();
    }

Xaml:

<Button x:Name="btn" Content="Button" HorizontalAlignment="Left" MouseEnter="btn_MouseEnter" MouseLeave="btn_MouseLeave" Click="btn_Click"/>

尝试为此使用System.Windows.Forms.Timer对象。

例如,假设您希望控件在光标达到三(3)秒后运行MessageBox,这就是您可以做的:

[C#]

// Used to store the counting value.
private int _counter = 0;
private void control_MouseHover(object sender, EventArgs e)
{
    // Create a new Timer object.
    Timer timer = new Timer();
    // Set the timer's interval.
    timer.Interval = 1000;
    // Create the Tick-listening event.
    _timer.Tick += delegate(object sender, EventArgs e) 
    {
        // Update the counter variable.
        _counter++;
        // If the set time has reached, then show a MessageBox.
        if (_counter == 3) {
            MessageBox.Show("Three seconds have passed!");
        }
    };
    // Start the timer.
    _timer.Start();
}

[VB.NET]

 Dim _counter As Integer 
 Private Sub Control_MouseHover(ByVal sender As Object, ByVal e As EventArgs) _
 Handles Control.MouseHover
    ' Create a new Timer object.
    Dim timer As New Timer()
    ' Set the timer's interval.
    timer.Interval = 1000
    ' Create the Tick-listening event.
    AddHandler _timer.Tick, Sub(sender As Object, e As EventArgs)
        ' Update the counter variable.
        _counter += 1
        ' If the set time has reached, then show a MessageBox.
        If _counter = 3 Then
            MessageBox.Show("Three seconds have passed!")
        End If
    End Sub
    ' Start the timer.
    _timer.Start()
End Sub

最新更新