PInvoke (some type this as p/Invoke) that is Platform Invoke is most awaited feature in Silverlight since the announcement of Roadmap of Silverlight 5.
Why I kept above text in Bold? This is because there is lot of HTML5 talks around and sometime people unnecessarily without judging pulling Silverlight down for no good reason.For those who think we are Dead or we are just Animation technology..well by this feature you folks must have realize the potential of this Silverlight platform and where we are heading towards.
Coming back to PInvoke,So today to start with,I am putting forward a very simple and basic demo of PInvoke for you to understand and grab the topic and get hold of it.Then in next article I will be putting some advance samples and also in coming days I will be covering few more Silverlight 5 topics as well.
This demo is based on calling a “Beep” functionality from kernel32.dll file from Windows
If your fundas of PInvoke are not clear,In that case I encourage you to have a look at this article on Wikipedia which talks about PInvoke
Our First Silverlight PInvoke Demo : Beep !!..Beep !!…
This is the primary namespace used to develop PInvoke apps.
<Grid x:Name="LayoutRoot" Background="Black">
I just taken a Road Runner Image as name of the demo is Beep Beep
C# Code :
Now what we are going to do is that we will invoke Beep function which is a System Beep function from kernel32.dll
#region Beep Module
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool Beep(uint dwFreq, uint dwDuration);
[DllImport…] specified which dll file we are invoking.”SetLastError” is actually a Named Parameter in the signature which indicate whether the callee calls the SetLastError Win32 API function before returning from attribute method.
So we are all set to call Beep function from kernel32.dll in our Silverlight app like shown below :
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
void MainPage_Loaded(object sender, RoutedEventArgs e)
for (uint i = 100; i <= 200; i=i+10)
Done ! We have just develop our first PInvoke Sample using Silverlight 5 RC !
Now turn on your speakers and get ready to hear Beep !! Beep !! from Road Runner ..I mean you will get some sound / default sound from system.If you want to change bits and duration then go ahead and feel free to tune the code.
Oh ! Wait ! What’s this error about? :
This is Runtime Exception because of lacking of trust,so you need to turn on that in OOB setting like this :
To know more on this Trust part I encourage you to read my friend Kunal’s article here.
Output : (Turn On the Speakers for Beep)
This ends our first ever PInvoke functionality using Silverlight 5 RC.I request you to download new RC bits and try out this demo,meanwhile I will prepare my next advance demo of PInvoke and other few articles.So with this PInvoke I can say again that ..Future is Bright ! Future is Silverlight !!