Sunday, September 04, 2011

Silverlight 5 RC Released - Using PInvoke

   It's exciting to see the progress of Silverlight 5 toward the final release that has been slated towards the end of the year. Today, the Silverlight Team announced the release of the Silverlight 5 Release Candidate. While it does not yet have a go-live license, it integrates many new features that were not available with the beta release, including the new PivotViewer integration and vector-based printing.

One of the new features included with the Silverlight 5 RC is the ability to interact with Platform Invocation Services, or PInvoke for short. This functionality allows managed code, like your Silverlight application, to make calls to unmanaged code like the C++ code that exists in DLLs on your system. PInvoke can be quite complex and covers a lot of different scenarios, so I've focused on a simple scenario to help you get started. You can learn more about PInvoke by reading this MSDN tutorial.

In this post, I will show you how to build a Silverlight Out-of-Browser (OOB) application that uses the native DLLs on your machine to play "beeps." With modern versions of Windows 7, the beeps have evolved into complex sounds that you can assign to various functions. Create a new Silverlight application called "PInvoke," set it to run out of browser and be sure to check the box that indicates it requires elevated trust.

Take a look at the MessageBeep function. It is documented here. The first thing you'll notice is that the type of beep or sound to play is not very friendly as it is passed in as an unsigned integer. Based on the documentation, you can create the following enumeration to simplify things and expose a few key types:

public enum BeepTypes : uint
{
    Ok = 0x00000000,
    Error = 0x00000010,
    Warning = 0x00000030,
    Information = 0x00000040
}

To make it easy to take a string and cast it to the enumeration value, add this extension method as well:

public static class BeepTypeExtensions
{
    public static BeepTypes AsBeepTypeEnum(this string beepType)
    {
        BeepTypes beepTypeEnum;
        return Enum.TryParse(beepType, true, out beepTypeEnum)
                    ? beepTypeEnum
                    : BeepTypes.Error;
    }
}


Read more: C#er: IMage
QR: silverlight-5-rc-released-using-pinvoke.html

Posted via email from Jasper-Net