Sunday, June 8, 2008

How to detect NO mouse movement

In some occasions you might want to show or hide stuff in your Silverlight application when the visitor stopped moving his/her mouse.
For instance, most media players use this method to hide the play/pause/forward/mute controlbar.

You can achieve this by doing following this:

1. Create a DispatcherTimer

private DispatcherTimer _nomousemoveTimer = new DispatcherTimer();

2. Use the constructor of your class to create eventhandlers for events listed below and set the interval of the DispatcherTimer (in this case I set it to 3 seconds):
this.MouseMove += new MouseEventHandler(Page_MouseMove);
this.Loaded += new RoutedEventHandler(Page_Loaded);
_nomousemoveTimer.Tick += new EventHandler(_nomousemoveTimer_Tick);
_nomousemoveTimer.Interval = new TimeSpan(0, 0, 3);

3. In the Page Loaded, start the timer:

4. Now, in the Page_MouseMove event, stop the timer and start it immediately after stopping it:

5. Finally, in the Tick event of the timer, execute your code:
private void _nomousemoveTimer_Tick(object sender, EventArgs e)
//do your stuff

Click here to view the demo

Click here to download the source

1 comment:

  1. You can also kick off a storyboard for say a mouseover the control area, but not have anything happen for x (milli)seconds in the storyboard.
    If your mouse exits you kick off your exit storyboard (or stop your first one)