I would like for a program to play a beep as long as a specific key is pressed. Is there any way in which i can detect a key when it's released? and then abort a thread which plays that beep?
Consider the following example:
class Program
{
public static void Play()
{
while (true)
{
Console.Beep(400, 10000);//play for a long length, will be interrupted as soon as the key is released
}
}
public static void Main(string[] args)
{
while(true)
{
ConsoleKeyInfo cki=Console.ReadKey(true);
if(cki.Key==ConsoleKey.G)
{
Thread p = new Thread(Play);
p.Start();
}
}
}
I considered using Thread.Abort()
, However it should only abort the aforementioned thread p when the key G is released.
Implementing a method which plays the beep for a short length while keeping the G key pressed wont work , since small intervals can be heard between each beep.
Therefore, using the following code will play short beeps with small intervals between them:
public static void Main()
{
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
Console.Beep(400, 10);
}
while (keyinfo.Key == ConsoleKey.G);
}
Instead i would like to have one long beep, stopped as soon as a key is released.