views:

77

answers:

4

I would like to delay an action by several seconds after a mouse pointer has entered and remained for period of time in a winform graphics rectangle. What would be a way to do this?

Thanks

c#, .net 2.0, winform

A: 

Try using the Timer control (System.Windows.Forms.Timer).

DxCK
+1  A: 

Something such as:

    static void MouseEnteredYourRectangleEvent(object sender, MouseEventArgs e)
    {
        Timer delayTimer = new Timer();
        delayTimer.Interval = 2000; // 2000msec = 2 seconds
        delayTimer.Tick += new ElapsedEventHandler(delayTimer_Elapsed);
    }

    static void delayTimer_Elapsed(object sender, EventArgs e)
    {
        if(MouseInRectangle())
            DoSomething();

        ((Timer)sender).Dispose();
    }

Probably could be done more efficiently, but should work :D

Two ways to set up MouseInRectangle -> one is to make it get the current mouse coordinates and the position of the control and see if it's in it, another way would be a variable which you would set to false on control.mouse_leave.

Blam
Although this is an acceptable answer, it's important to note that @Blam did not dispose the Timer object that was created when it was sent to false. You should ((Timer)sender).Dispose() to free up the resources allocated by the Timer.
Michael
You're right - fixed. To be honest Martin's is better in general :P
Blam
+2  A: 
private Timer timer;
    private void rect_MouseEnter(object sender, EventArgs e)
    {
        timer = new Timer();
        timer.Interval = 3000;
        timer.Start();
        timer.Tick += new EventHandler(t_Tick);

    }

    private void rect_MouseLeave(object sender, EventArgs e)
    {
        timer.Dispose();
    }

    void t_Tick(object sender, EventArgs e)
    {
        timer.Dispose();
        MessageBox.Show(@"It has been over for 3 seconds");
    }
Martin Beeby
A: 

Please notice System.Windows.Forms.Timer is not Exact and you cannot rely it will act on exactly the interval given. it would be prefeable to use System.Times.timer and use the Invoke action to return to the GUI thread.