I have a code that when mouse hovers a button then it fires click event.But i want that when mouse hovers for 3 seconds then event must be fired.I have used intervals but could not find out solution. I have a simple windows froms c# application.
I agree with you, but actually i am working on a project where i want to operate pc by using hand gestures rather then mouse. You may have seen different games and application for kinect. So i truly need this if any one can help me
There should be a hand gesture for click. It would be incredibly annoying if you only hovered it, especially accidentally, and then got stuck in a menu cycle of open and close because the detection wasn't working properly...
Not much tbh, these are trivial mistakes that can have a big impact.
There are several Timer classes. I normally make use of the System.Threading.Timer class as, in my opinion, this is the best of those available (but be warned, it's not thread-safe like you'd expect it to be)
First, move the Timer setup into the OnLoad or Constructor.
Second, in the constructor parameters for the Time, set the callback as your method, add a synchronisation object (if needed), set the dueTimeargument to Infinite and set the period argument to Infinite.
To start the timer, call the Change method on the timer and set the dueTime argument to 3000 and the period argument to Infinite. This will cause your callback to be invoked a single time after the given delay period (note that this won't include the time it takes for the "hover" to take place, so it will be something like 3.5 seconds)
Here's a code example:
using Timer = System.Threading.Timer;
public partial class Form1 : Form
readonly Timer _myTimer;
readonly Button button1 = new Button();
button1.Click += button1_Click;
button1.MouseHover += button1_MouseHover;
TimerCallback timerCallback = MyCallback;
_myTimer = new Timer(timerCallback, null, Timeout.Infinite, Timeout.Infinite);
private void button1_Click(object sender, EventArgs e)
// Do stuff
MessageBox.Show(@"There's a snake in mah booooots!");
private void button1_MouseHover(object sender, EventArgs e)
_myTimer.Change(3000, Timeout.Infinite); // timer will execute the callback after 3sec and only once
private void MyCallback(object stateInfo)
// This is better if you need to pass specific arguments.
if (button1.InvokeRequired) // This is almost a certainty, but best to check anyway
button1.Invoke(new Action(button1.PerformClick), null);
This will compile and work as an example :)
You can use the other timers too, set the interval to the required amount of time and Enable it. The problem I have with this, is that if your thread isn't marshalled properly (in time), there's a possiblity that the timer callback can execute a second time before you disable it. This becomes problematic at lower intervals.
To alleviate having to invoke, the forms timer will execute on the UI thread, but I really don't like that idea as you can deadlock easily.