Click here to Skip to main content
15,867,704 members
Articles / Desktop Programming / XAML
Article

How to use PInvoke in Silverlight 5

Rate me:
Please Sign up or sign in to vote.
4.82/5 (5 votes)
12 Sep 2011CPOL3 min read 44.2K   691   12   8
A look at how to get started working with P/Invoke in the Silverlight 5 RC.

Description: image

Introduction

You might have noticed that the Silverlight 5 (Release Candidate) is out. One of the new features included in the RC is the ability to call P/Invoke. In this short demo, we will write a Silverlight 5 application that uses the feature.

Tools needed:

Getting Started

Go ahead and open Visual Studio 2010 SP1 and select File->New Project, then Silverlight Application.

Description: SNAGHTML425f655

By default, we have a new option called “Silverlight 5” selected as the Silverlight version. Let’s go ahead and leave it at that. You also have the ability to select Silverlight 3 or 4 from this drop-down.

Description: SNAGHTML427e8ce

Let’s go ahead and right click on our project and select Properties.

Description: image

Put a check in “Enable running application out of the browser”.

Description: image

Now go ahead and put a check in “Require elevated trust when running outside the browser”.

Description: SNAGHTML2b29bb45

Switch back over to MainPage.xaml and add in the following code:

XML
<Grid x:Name="LayoutRoot" Background="White">
    <Button Height="23" HorizontalAlignment="Left" Margin="169,132,0,0" 
       VerticalAlignment="Top" Width="75" x:Name="btnclick" 
       Content="click" Click="click_Click" />
</Grid>

This will simply put a no thrills button on the page that the user can press to call the P/Invoke code we will add shortly.

Let’s go ahead and add a new class to the project.

Description: image

Let’s call it PlatformInvokeTest.cs and add the following code (Note: If you are having a problem getting it to work, then use my solution at the bottom of the post):

C#
using System;
using System.Runtime.InteropServices;
 
namespace SilverlightApplication26
{
    public class PlatformInvokeTest
    {
        [DllImport("kernel32.dll")]
        public static extern bool Beep(int frequency, int duration);
 
    
        public static void PlaySound()
        {
            Random random = new Random();
            for (int i = 0; i < 50; i++)
            {
                Beep(random.Next(10000), 100);
            }
        }
    }
}

Let’s switch back over to MainPage.xaml.cs and add the following code:

C#
using System.Windows;
using System.Windows.Controls;
 
namespace SilverlightApplication26
{
 
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        private void click_Click(object sender, RoutedEventArgs e)
        {
            PlatformInvokeTest.PlaySound();
        }
    }
}

Now when the user fires up this project, the application will go out of browser and the computer will beep multiple times in a different frequency each time.

You can also get this same functionality in-browser by going back to the Properties page and selecting “Require elevated trust when running in-browser”.

Description: image

The only thing to note is that the .aspx page is no longer set to the default in your web project so you will need to do a “View in Browser” on your .aspx page in order to test.

Description: image

Conclusion

As you can see, it is very easy to use P/Invoke in a Silverlight 5 application. This sample was pretty simple but imagine the possibilities such as detecting when a USB key is inserted into a PC and copying files onto it through a Silverlight 5 application. Pretty cool stuff!

If you want the source code to this application and other Silverlight 5 demos, then be sure to check out Michael’s “Mega Collection of #Silverlight 5" Demos.

Resources

Other Silverlight 5 resources by me are listed below:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Telerik
United States United States
Michael Crump is a Silverlight MVP and MCPD that has been involved with computers in one way or another for as long as he can remember, but started professionally in 2002. After spending years working as a systems administrator/tech support analyst, Michael branched out and started developing internal utilities that automated repetitive tasks and freed up full-time employees. From there, he was offered a job working at McKesson corporation and has been working with some form of .NET and VB/C# since 2003.

He has worked at Fortune 500 companies where he gained experience in embedded systems design and software development to systems administration and database programming, and everything in between.

His primary focus right now is developing healthcare software solutions using Microsoft .NET technologies. He prefers building infrastructure components, reusable shared libraries and helping companies define, develop and automate process standards and guidelines.

You can read his blog at: MichaelCrump.net or follow him on Twitter at @mbcrump.

Comments and Discussions

 
QuestionThe sound not coming after the deployment Pin
Rajamohan.Rajendran17-Aug-14 20:49
Rajamohan.Rajendran17-Aug-14 20:49 
i have deployed the sample application to my local IIS. i am getting sound when i am access like this.
http://localhost/ReaderSilverlight/SilverlightApplication1TestPage.html[^]
but sound not coming from other system using my system IP address like this
http://10.151.50.141/ReaderSilverlight/SilverlightApplication1TestPage.html[^]

Can you help me!!!
GeneralMy vote of 5 Pin
Massimo Conti29-Jun-12 13:12
Massimo Conti29-Jun-12 13:12 
Questionno beep when I pointed IE9 to ..SLtest\Bin\Debug\SLtestTestPage.html Pin
piero821-Dec-11 9:27
piero821-Dec-11 9:27 
GeneralNice Pin
Kunal Chowdhury «IN»12-Sep-11 6:03
professionalKunal Chowdhury «IN»12-Sep-11 6:03 
QuestionP/Invoke... Pin
Guillermo Rivero12-Sep-11 4:38
Guillermo Rivero12-Sep-11 4:38 
AnswerRe: P/Invoke... Pin
dave.dolan12-Sep-11 10:48
dave.dolan12-Sep-11 10:48 
GeneralRe: P/Invoke... Pin
Massimo Conti29-Jun-12 22:16
Massimo Conti29-Jun-12 22:16 
GeneralRe: P/Invoke... Pin
jlsfernandez16-May-13 3:39
jlsfernandez16-May-13 3:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.