Share via


TabletPC Development Gotchas Part 7: Detecting the input device in Silverlight 2

When writing an application that supports multiple input devices (mouse, stylus, touch) it is often neccessary to detect which type of device is sending the input events.Silverlight 1.0 offered a DeviceType property on the StylusInfo object that gets reported in every mouse event.

In the Silverlight 2 managed API, you will not find an equivelnt object that provides this information. We omitted it on purpose in this release, because adding this to the OM could not be done in a way that would make the Silverlight API a compatible subset of the WPF API. In future versions of both platforms we will provide a consistent way to get to this information.

Omitting this for now is acceptable since we do provide a workaround to get to this information, via the HTML DOM bridge. Here is how you do it (full source attached):

 

Expose a scriptable method from managed code to handle the DeviceType information:

 

    public Page()

    {

        InitializeComponent();

        HtmlPage.RegisterScriptableObject("page", this);

    }

    [ScriptableMember]

    public void SetDeviceType(string deviceType)

    {

        _deviceType = deviceType;

        switch (_deviceType)

        {

            case "Mouse":

                // add specific code for mouse

                break;

            case "Stylus":

                // add specific code for stylus

                break;

            case "Touch":

             // add specific code for touch

                break;

        }

    }

 

Hook up to the MouseLeftButtonDown event in JavaScript and pass the StylusInfo.DeviceType information to managed code when the event fires:

 

<script type="text/javascript">

function onSilverlightLoad(sender, args) {

// attach a JavaScript MouseDown event handler

var inkPresenter = sender._element.content.findName("inkPresenter");

inkPresenter.addEventListener("mouseLeftButtonDown", onMouseDown);

}

function onMouseDown(sender, args) {

// get the device type info and pass

// the information to the managed code

var stylusInfo = args.getStylusInfo();

var plugin = sender.getHost();

plugin.content.page.SetDeviceType(stylusInfo.deviceType.toString());

}

</script>

Now, as a proud owner of a Toshiba M700, I can run the solution and collect ink from different devices and the app automatically changes the pen attributes as I switch between input devices. Here is a screenshot showing ink strokes collected with the three different devices available on my Tablet PC:

Input Device Detection Sample

InputDeviceDetection.zip