简体   繁体   中英

How to delay mouse hover time?

I'm making an application in C#. Whenever I hover cursor on a button message should be displayed. Also if I hover for about 3 seconds again a message should be displayed that 'Your mouse has been hovering for 3 seconds' on button.

Try using this to solve the problem:

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

You have to set a timer and use MouseEnter/MouseLeave events as shown below:

    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"/>

Try using a System.Windows.Forms.Timer object for this.

For example, say you want your control to run a MessageBox after the Cursor has reached three (3) seconds, this is what you can do:

[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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM