Right Click event in Silverlight 1.1/2.0

1 Comment December 9, 2007

There are many mouse events raised in Silverlight 1.1/2.0, but you will notice that right click is not one of them.  This is because by default the Silverlight plug-in hooks the right click to show information about Silverlight and update settings.  So what do you do if you have a feature such as a context menu that relies on the right click event?  Don't fret, JavaScript interaction with managed code comes to the rescue.

First you hook the right click event with your own JavaScript function.

function click(e)
    var control = document.getElementById("SilverlightControl");

    if (navigator.appName == "Netscape" && e.which==3)
        alert(e.clientX + " " + e.clientY);
        control.Content.PageReference.RightMouseButtonDown(e.clientX, e.clientY);
        return false;

    if (navigator.appName == "Microsoft Internet Explorer" && event.button==2)
        alert(event.clientX + " " + event.clientY);
        control.Content.PageReference.RightMouseButtonDown(event.clientX, event.clientY);
        return false;

    return true;


Fig 1. (JavaScript) Hooking right click event and passing to managed code
In the above code snippet you get a reference to the SilverLight plug-in and from there you can call your managed code method.  So in this case the JavaScript is calling a managed code method called RightMouseButtonDown that accepts the current mouse X and Y coordinates as input parameters.
Next you move over to managed code.  There are two steps that need to be taken for a managed code method to be called from JavaScript.  First you will need to register the class itself as callable from JavaScript.  You do this by registering the class as a scriptable endpoint and giving it a string reference name.  This code uses "PageReference" as the string reference name since the class name is "Page". 

//Register the page class, "this", as a scriptable endpoint
WebApplication.Current.RegisterScriptableObject("PageReference", this);

Fig 2. (Managed Code) Registering the page class as a scriptable endpoint
Finally you decorate the managed code method that is to be called from JavaScript with the [Scriptable] attribute.  Once this is done the right click event will be hooked from JavaScript and passed on or "raised" to the appropriate managed code method.

public void RightMouseButtonDown(int x, int y)
     // Do some work here
     // such as displaying a context menu

Fig 3. (Managed Code) RightMouseButtonDown method decorated with [Scriptable] attribute
That's it!  Now you have a managed code method that will be called when the user clicks the right mouse button.

1 Comment

Have a Comment?


None found