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

วิธีเคลียร์หน้าจอคอนโซลใน C# (Console.Clear)


ภาพรวม

เมธอด Console.Clear() ใช้ ล้างหน้าจอคอนโซลและบัฟเฟอร์ ย้ายเคอร์เซอร์ไปมุมบนซ้าย (0,0)

ตัวอย่างโค้ดเต็ม

using System;

class Program
{
    static void Main()
    {
        ConsoleColor foreColor = Console.ForegroundColor;
        ConsoleColor backColor = Console.BackgroundColor;
        Console.WriteLine("Clearing the screen!");
        Console.Clear();
        ConsoleColor newForeColor = ConsoleColor.Blue;
        ConsoleColor newBackColor = ConsoleColor.Yellow;
    }
}

ผลลัพธ์

Clearing the screen!
(หน้าจอถูกล้าง เคอร์เซอร์อยู่มุมบนซ้าย)

ข้อสังเกต

  • ทำงานได้เฉพาะในสภาพแวดล้อมที่มีคอนโซลจริง (console application)
  • ในบาง IDE (เช่น Visual Studio Output Window) อาจไม่ทำงานหรือโยน IOException
  • ควรใช้ try-catch ครอบ: try { Console.Clear(); } catch (IOException) { }
  • ไม่ล้าง Console.Error output stream