เมธอด Console.ReadKey() ใน C#
Console.ReadKey() ใช้หยุดโปรแกรมรอผู้ใช้กดปุ่มคีย์บอร์ด ป้องกันหน้าต่าง Console ปิดทันทีเมื่อรันจาก Visual Studio และสามารถตรวจสอบปุ่มที่กดได้
การใช้งานพื้นฐาน
Console.WriteLine("Press any key to continue...");
Console.ReadKey(); // หยุดรอการกดปุ่ม
ตัวอย่าง: รอจนกว่าจะกด Enter
using System;
public class Demo
{
public static void Main()
{
DateTime date = DateTime.Now;
TimeZoneInfo timeZone = TimeZoneInfo.Local;
Console.WriteLine("Time Zone = {0}",
timeZone.IsDaylightSavingTime(date) ? timeZone.DaylightName : timeZone.StandardName);
Console.Write("Press Enter to exit... ");
// วนลูปรอจนกว่าจะกด Enter
while (Console.ReadKey().Key != ConsoleKey.Enter)
{
// ไม่ทำอะไร รอต่อไป
}
}
}
ผลลัพธ์
Time Zone = UTC
Press Enter to exit...
ข้อมูลที่ได้จาก ConsoleKeyInfo
| Property | คำอธิบาย |
|---|---|
Key | ปุ่มที่กด (Enum ConsoleKey) |
KeyChar | ตัวอักษรที่กด (char) |
Modifiers | ปุ่ม Modifier (Shift, Alt, Ctrl) |
ตัวอย่างตรวจสอบ Modifier Keys
var keyInfo = Console.ReadKey(true); // true = ไม่แสดงตัวอักษรบนหน้าจอ
if (keyInfo.Key == ConsoleKey.S && keyInfo.Modifiers == ConsoleModifiers.Control)
{
Console.WriteLine("Ctrl+S ถูกกด!");
}