Console.ReadKey() đọc một phím nhấn từ bàn phím (bao gồm ký tự, phím chức năng, phím modifier) và trả về đối tượng ConsoleKeyInfo. Thường dùng để:
- Giữ cửa sổ console mở (tránh đóng ngay khi chạy từ Visual Studio).
- Tạm dừng chương trình chờ người dùng nhấn phím.
- Xử lý nhập phím đơn lẻ (menu, game, điều khiển...).
Nạp chồng (Overloads)
| Phương thức | Mô tả |
|---|---|
ReadKey() | Đọc phím và hiển thị ký tự ra console. |
ReadKey(bool intercept) | intercept=true: Đọc phím nhưng không hiển thị ký tự (dùng cho mật khẩu, game). |
Ví dụ 1: Giữ console mở
using System;
class Program
{
static void Main()
{
Console.WriteLine("Chương trình chạy xong.");
Console.Write("Nhấn phím bất kỳ để thoát... ");
Console.ReadKey(); // Chờ nhấn phím
}
}
Ví dụ 2: Menu điều khiển (ReadKey(true) - không hiển thị)
using System;
class Program
{
static void Main()
{
Console.WriteLine("=== MENU ===");
Console.WriteLine("1. Xem thông tin");
Console.WriteLine("2. Cài đặt");
Console.WriteLine("ESC. Thoát");
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(true); // intercept = true
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.WriteLine("\n→ Đang xem thông tin...");
break;
case ConsoleKey.D2:
case ConsoleKey.NumPad2:
Console.WriteLine("\n→ Mở cài đặt...");
break;
case ConsoleKey.Escape:
Console.WriteLine("\n→ Tạm biệt!");
return;
default:
Console.WriteLine("\n→ Phím không hợp lệ!");
break;
}
}
}
}
Ví dụ 3: Đọc mật khẩu (ẩn ký tự)
using System;
using System.Text;
class Program
{
static void Main()
{
Console.Write("Nhập mật khẩu: ");
StringBuilder password = new StringBuilder();
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(true); // Không hiển thị
if (key.Key == ConsoleKey.Enter)
break;
else if (key.Key == ConsoleKey.Backspace && password.Length > 0)
{
password.Length--;
Console.Write("\b \b"); // Xóa dấu * trên màn hình
}
else if (!char.IsControl(key.KeyChar))
{
password.Append(key.KeyChar);
Console.Write("*"); // Hiển thị * thay vì ký tự thật
}
}
Console.WriteLine($"\nMật khẩu đã nhập: {password}");
}
}
Cấu trúc ConsoleKeyInfo
| Thuộc tính | Kiểu | Mô tả |
|---|---|---|
Key | ConsoleKey | Mã phím (Enter, Esc, A, F1...) |
KeyChar | char | Ký tự Unicode (0 nếu phím chức năng) |
Modifiers | ConsoleModifiers | Phím kết hợp: Shift, Alt, Control |
Lưu ý: ReadKey() không hoạt động trong một số môi trường không có console thực (như một số IDE online, redirected output).