Mục đích
Console.Beep() phát âm beep hệ thống (PC speaker). Có 2 nạp chồng: không tham số (mặc định) và có tần số/thời lượng.
Ví dụ 1: Beep mặc định
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine("Standard Output Stream: " + Console.Out);
Console.WriteLine("Phát beep...");
Console.Beep();
}
}
Kết quả
Standard Output Stream: System.IO.TextWriter+SyncTextWriter
Phát beep...
Ví dụ 2: Beep có tần số và thời lượng
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine("Standard Output Stream: " + Console.Out);
Console.WriteLine("Beep mặc định...");
Console.Beep();
Console.WriteLine("Beep 1000Hz, 500ms...");
Console.Beep(1000, 500);
}
}
Kết quả
Standard Output Stream: System.IO.TextWriter+SyncTextWriter
Beep mặc định...
Beep 1000Hz, 500ms...
Tham số
frequency: 37 - 32767 Hz.duration: > 0 milliseconds.
Lưu ý
- Chỉ **Windows** (PC speaker/buzzer).
- Không qua loa âm thanh bình thường (trừ một số hardware cũ).
- VM, Remote Desktop, Container: thường im lặng.
- Không điều khiển âm lượng.
- Cross-platform: dùng
System.Media.SoundPlayer(Windows, .wav) hoặc thư viện NAudio, Silk.NET.
Ví dụ: Cảnh báo Caps Lock khi nhập mật khẩu
using System;
public class Demo
{
public static string ReadPassword()
{
string pwd = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Enter && key.Key != ConsoleKey.Backspace)
{
if (Console.CapsLock)
{
Console.Beep(800, 100); // Cảnh báo
}
pwd += key.KeyChar;
Console.Write("*");
}
else if (key.Key == ConsoleKey.Backspace && pwd.Length > 0)
{
pwd = pwd[..^1];
Console.Write("\b \b");
}
} while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
return pwd;
}
}