DCSIMG
Quick Tip – Making Beep From the PC Speaker Using P/Invoke - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2011 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

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 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!

Comments

Jim Danby said:

...or use the Beep method.

# February 26, 2010 6:00 PM

Gil Fink said:

@Jim Danby,

Yes we could use the Console.Beep() method which invoke the same method underneath.

# February 26, 2010 6:38 PM