May 19th, 2009
Zoom in and out using the Mouse wheel in Silverlight
7 Comments, Silverlight 2 tutorials, Silverlight C# Tutorials, Silverlight Effects, by Gavin Wignall.First off I add the following reference at the top of my C# file so that we can interact with the browser;
using System.Windows.Browser;
To then listen for the Mouse wheel interaction I set events in the browser using the following piece of C#;
HtmlPage.Window.AttachEvent(“DOMMouseScroll”, OnMouseWheel);
HtmlPage.Window.AttachEvent(“onmousewheel”, OnMouseWheel);
HtmlPage.Document.AttachEvent(“onmousewheel”, OnMouseWheel);
I can then check for a value to see if the mouse wheel is being moved forward or backward using the following Method;
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);
}
This now gives me a value in the form of ‘mouseDelta’ which can be applied to what ever you want your interaction to be. In this case we are controlling the scale factor of a canvas.
To limit the scale factor I run a check to see if the scale value has gone under 1 or over 10 and if so reset the value to the minimum or maximum amount;
if (ScaleFactor.ScaleX < 1)
{
ScaleFactor.ScaleX = 1;
ScaleFactor.ScaleY = 1;
}
if (ScaleFactor.ScaleX > 10)
{
ScaleFactor.ScaleX = 10;
ScaleFactor.ScaleY = 10;
}
I also check where the mouse cursor is and focus the zoom in / out on that position. I do this by storing the mouse co-ordinates everytime the user moves their mouse and then changing the ‘RenderTransformOrigin’ value;
//get mouse co-ordinates
void zoomArea_MouseMove(object sender, MouseEventArgs e)
{
pt = e.GetPosition(zoomArea);
}
//change the RenderTransformOrigin
zoomArea.RenderTransformOrigin = new Point(pt.X / zoomArea.Width, pt.Y / zoomArea.Height);
Get the code
You can download the above example here.