Quick Tip – Making Beep From the PC Speaker Using P/Invoke
Quick Tip – Making Beep From the PC Speaker Using P/Invoke
I was asked yesterday
how can we perform
a beep sound from the
PC speaker. This is
something that is
needed in one of the
applications that I’m consulting for to indicate a
successful transaction (don’t ask me way…).
Setting the Environment
We first need to add the using for Runtime.InteropServices:
using System.Runtime.InteropServices;
Then load the unmanaged dll of kernel32.dll with the
method signature for Beep which get two uint parameters
one for frequency and the second for duration in milliseconds:
[DllImport("kernel32.dll")]
static extern bool Beep(uint frequency, uint duration);
Beep, Beep, Beep
After we set the environment all we have to do is call the beep
method. For example:
using System.Runtime.InteropServices;
namespace Beep
{
class BeepExample
{
[DllImport("kernel32.dll")]
static extern bool Beep(uint frequency, uint duration);
static void Main()
{
Beep(2500, 1000);
}
}
}
Summary
If you need to beep now you know how.
Enjoy!