Friday, February 20, 2009

Capturing mouse scroll / wheel event in Silverlight

Silverlight doesn't support mouse wheel event. There is a way to catch them if we ask to the browser for them. This workaround works well if the page with your Silverlight application fits in the browser. If the page is bigger in height a scroll appears. Then the whole content of the page is scrolled and the SL application doesn't receive the wheel event until one end is reached.
Hook up to the event. Different names are used in the different browsers.
C#
using System.Windows.Browser;...
HtmlPage.Window.AttachEvent( "DOMMouseScroll", OnMouseWheel ); // MozillaHtmlPage.Window.AttachEvent( "onmousewheel", OnMouseWheel );HtmlPage.Document.AttachEvent( "onmousewheel", OnMouseWheel ); // IE
This is how you get the wheel delta.
C#
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 );}

That's it!

1 comment: