How To Handle RightClick Mouse Event in Silverlight

February 7, 2008

Ever tried to get right click event from Silverlight and always got this?

image

Today I’ll give 5 minutes recipe of how to get rid of this "Silverlight Configuration" popup and receive right click mouse events in manage code.

Lets make default "New Silverlight Project".

Well, first of all, lets do some XAML – my page will be very simple:

<Canvas x:Name="parentCanvas"
        xmlns="http://schemas.microsoft.com/client/2007" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Loaded="Page_Loaded" 
        x:Class="RightClick.Page;assembly=ClientBin/RightClick.dll"
        Width="640"
        Height="480"
        >

  <Canvas.Background>
    <LinearGradientBrush StartPoint="0.5,-1" EndPoint="0.5,1">
      <GradientStop Color="#FF718398" Offset="0"/>
      <GradientStop Color="#FFFFFFFF" Offset="1"/>
    </LinearGradientBrush>
  </Canvas.Background>
  <TextBlock Canvas.Top="10" Canvas.Left="10" x:Name="txt" Text="Silverlight" FontFamily="Segoe" FontSize="25" FontWeight="Bold" Foreground="Blue"/>
</Canvas>

 

Now lets modify a little standard HTML page, which will host it (TestPage.html):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Silverlight Project Test Page </title>
    
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript" src="TestPage.html.js"></script>
    <style type="text/css">
        .silverlightHost { width: 640px; height: 480px; position:absolute; }
    </style>
    
    <script type="text/javascript">
    function ReactOnClickEvent()
    {
        var silverlightControl = document.getElementById("SilverlightControl");
        
        if(silverlightControl)
            silverlightControl.Content.ActualSilverlightControl.ProcessMouseEvent(event);
    }
    </script>
</head>

<body oncontextmenu="return false;">
    <div id="SilverlightControlHost" class="silverlightHost" onmousedown="ReactOnClickEvent();">
        <script type="text/javascript">
            createSilverlight();
        </script>
    </div>
</body>
</html>

There are 2 important changes in this standard file, which I did:

1. Added handler function to "onmousedown" event (it could be also "onmouseup") called "ReactOnClickEvent" which executes some managed code.

2. Added "oncontextmenu" event handler to our body.

Now let’s make 1 small change in our standard TestPage.html.js page:

Add property value isWindowless: "true" in CreateSilverlight() function like this:

//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight()
{
    Silverlight.createObjectEx({
        source: "Page.xaml",
        parentElement: document.getElementById("SilverlightControlHost"),
        id: "SilverlightControl",
        properties: {
            width: "100%",
            height: "100%",
            version: "1.1",
            enableHtmlAccess: "true",
            isWindowless: "true"
        },
        events: {}
    });
       
    // Give the keyboard focus to the Silverlight control by default
    document.body.onload = function() {
      var silverlightControl = document.getElementById('SilverlightControl');
      if (silverlightControl)
      silverlightControl.focus();
    }
}

Finally let’s add some managed code:

   1: [Scriptable]
   2: public partial class Page : Canvas
   3: {
   4:     public void Page_Loaded(object o, EventArgs e)
   5:     {
   6:         // Required to initialize variables
   7:         InitializeComponent();
   8:  
   9:         WebApplication.Current.RegisterScriptableObject("ActualSilverlightControl", this);
  10:     }
  11:  
  12:     [Scriptable]
  13:     public void ProcessMouseEvent(ScriptableObject evt)
  14:     {
  15:         int button = evt.GetProperty<int>("button");
  16:         int clientX = evt.GetProperty<int>("ClientX");
  17:         int clientY = evt.GetProperty<int>("ClientY");
  18:  
  19:         txt.Text += "\n" + "Event from " + (button == 1 ? "Left" : "Right") + " mouse button on X=" + clientX + " Y = " + clientY;
  20:     }
  21:  
  22: }

Points here:

1. Mark your class as [Scriptable] (Line 1)

2. Register this class as ScriptableObject in Page_Loaded event (Line 9)

3. Add some function, which will be executed from JavaScript and process event parameters (in our case mouse parameters – Line 13)

Don’t forget to mark it as [Scriptable] too (Line 12)

That’s it… We done. Now lets run it:

image

 

"Silverlight Configuration" is gone… Right click event received in Silverlight and could been handled in the way we want…

Mission accomplished.

 

Enjoy!

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

5 comments

  1. RaviMay 27, 2008 ב 18:30

    Use full code…but Requires sample …
    As this code refers to RightClick.dll…that is no where available.
    thanks in advance.

    Reply
  2. Alex GoleshMay 28, 2008 ב 8:08

    Hi,

    This sample was good for Silvelright 1.1 alpha. I’ve posted update (http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2008/05/28/how-to-handle-rightclick-mouse-event-in-silverlight-take-2.aspx) with attached sources.

    Regards,
    Alex

    Reply
  3. LiuJuly 21, 2008 ב 12:06

    Hi,

    Does it work with Firefox ?

    Thanks in advance.

    Reply
  4. AlannaMarch 10, 2009 ב 15:04

    I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

    Alanna

    http://www.craigslistsimplified.info

    Reply