Back in May 2008, I wrote a blog post about checking for Win32 methods. I was recently reminded of this when a customer emailed us about a scenario that exactly matched the intended use case.
The customer was using the Smart Device Framework with a Windows CE 5.0 device and was receiving a MissingMethodException "Can't find an Entry Point 'xxx' in a PInvoke DLL 'yyy'". The exception message is detailed enough to explain the situation -- since Windows CE is modular, whoever created the OS image had not added a required component, resulting in the native functions to be missing from coredll.dll. This is not an uncommon scenario in the Windows CE world.
Below is an example of how you can gracefully handle calling the PlaySound function from coredll.dll even on devices that don't support the function. The important part is the call to Device.Win32Library("coredll").HasMethod("PlaySound"). This is return false if coredll.dll does not exist or if coredll.dll does not export the PlaySound function. Of course, you could raise a PlatformNotSupportedException or try another mechanism for playing the sound file instead of just returning without calling the native PlaySound function. The important point is that you should code in a way that can handle scenarios where the native function is not available and adapt accordingly.
Imports System.Runtime.InteropServices
Imports OpenNETCF.Reflection
Partial Public Class MainForm
Friend Class NativeMethods
Private Const SND_ASYNC As Integer = &H1
Private Const SND_FILENAME As Integer = &H20000
Public Shared Sub SafelyPlaySound(ByVal soundFile As String)
If Not Device.Win32Library("coredll").HasMethod("PlaySound") Then
Exit Sub ' Function is not exported so we silently return
End If
' Coredll exists and the PlaySound function has been exported
' so we can safely make the P/Invoke call
PlaySound(soundFile, IntPtr.Zero, SND_ASYNC And SND_FILENAME)
End Sub
_
Private Shared Function PlaySound(ByVal szSound As String, _
ByVal hMod As IntPtr, _
ByVal flags As Integer) As Integer
End Function
End Class
End Class