Your declaration of PlaySound
is wrong in a variety of ways.
First of all, do not set SetLastError
to true
. The documentation of PlaySound
makes no mention of GetLastError
, which means that PlaySound
makes no promise to call SetLastError
. The only error reporting it does is via its return value.
It is easier to declare the return type to be bool
, which is a better match for C++ BOOL
.
Finally, having gone to the trouble of declaring that nice enum, you may as well use it in your p/invoke. Put it together like this:
[DllImport("winmm.dll")]
public static extern bool PlaySound(
string szSound,
IntPtr hModule,
PlaySoundFlags flags
);
Also do note that Win32 API functions do not throw exceptions. These API functions are designed for interop and not all languages support SEH exception handling. So it will not throw, and indicates errors only by the boolean return value.
Your calling code should be:
public static void Play(string fileName)
{
if (!PlaySound(fileName, IntPtr.Zero,
PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_SYNC))
{
MessageBox.Show("Can't play sound file.");
}
}
Note that the final parameter of PlaySound
has type DWORD
. That's an unsigned 32 bit integer and so strictly speaking your enum should use uint
as its base type.