Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้เมธอด Console.ReadKey() ใน C#

เมธอด 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 ถูกกด!");
}