Quick Tip – Making Beep From the PC Speaker Using P/Invoke

February 26, 2010

2 comments

Quick Tip – Making Beep From the PC Speaker Using P/Invoke

I was asked yesterdayQuick Tip – Making Beep From the PC Speaker
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!

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2 comments

  1. Jim DanbyFebruary 26, 2010 ב 18:00

    …or use the Beep method.

    Reply
  2. Gil FinkFebruary 26, 2010 ב 18:38

    @Jim Danby,
    Yes we could use the Console.Beep() method which invoke the same method underneath.

    Reply