Share via


Silverlight Tip of the Day #23 – How to Capture the Mouse Wheel Event

Silverlight currently does not support mouse wheel events. However, you can attach an event to capture the mouse wheel movement through the HtmlPage object. This tutorial will show you how to do it for IE, Opera, Mozilla and Safari browsers.

To start, we declare three events to capture the mouse event in order to cover all the possibilities for all browsers. For example, the DOMMouseScroll event is used by Mozilla.

 public Page()
 {
     InitializeComponent();
  
     HtmlPage.Window.AttachEvent("DOMMouseScroll", OnMouseWheel);
     HtmlPage.Window.AttachEvent("onmousewheel", OnMouseWheel);
     HtmlPage.Document.AttachEvent("onmousewheel", OnMouseWheel);
 }

In our event we can get the delta change in the wheel. The way we do this in Mozilla and Safari browsers is different than how we do it in IE or Opera.

  1. Mozilla/Safari: Check the property called “detail”
  2. IE/Opera: Check the property called “wheeldelta”

Here is the complete code:

 private void OnMouseWheel(object sender, HtmlEventArgs args)
 {
     double mouseDelta = 0;
     ScriptObject e = args.EventObject;
  
     // Mozilla and Safari
     if (e.GetProperty("detail") != null) 
     {
         mouseDelta = ((double)e.GetProperty("detail"));
     }
     // IE and Opera
     else if (e.GetProperty("wheelDelta") != null) 
         mouseDelta = ((double)e.GetProperty("wheelDelta"));
  
     mouseDelta = Math.Sign(mouseDelta);
 }

Thank you,

--Mike Snow

 Subscribe in a reader