Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy kích thước cửa sổ Console lớn nhất (Height/Width) trong C#

Mục đích

Thuộc tính Console.LargestWindowHeight và Console.LargestWindowWidth trả về chiều cao/rộng tối đa (tính bằng ký tự) của cửa sổ console **trên màn hình hiện tại**, tính đến độ phân giải và font chữ.

Ví dụ 1: LargestWindowHeight

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Console.WriteLine($"Largest Window Height: {Console.LargestWindowHeight}");
    }
}

Kết quả (ví dụ)

Largest Window Height: 58

Ví dụ 2: LargestWindowWidth

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Console.WriteLine($"Largest Window Width: {Console.LargestWindowWidth}");
    }
}

Kết quả (ví dụ)

Largest Window Width: 190

Thuộc tính liên quan

Thuộc tínhMô tả
WindowHeight / WindowWidthKích thước cửa sổ hiện tại (có thể set).
BufferHeight / BufferWidthKích thước buffer (scrollback).
LargestWindowHeight/WidthGiới hạn tối đa trên màn hình hiện tại (read-only).

Ví dụ: Thiết lập cửa sổ to nhất có thể

using System;

public class Demo
{
    public static void Main()
    {
        try
        {
            Console.WindowHeight = Console.LargestWindowHeight;
            Console.WindowWidth = Console.LargestWindowWidth;
            Console.WriteLine("Đã set cửa sổ to nhất.");
        }
        catch (PlatformNotSupportedException)
        {
            Console.WriteLine("Không hỗ trợ set window size trên nền tảng này.");
        }
        catch (ArgumentOutOfRangeException)
        {
            Console.WriteLine("Kích thước không hợp lệ.");
        }
    }
}

Lưu ý

  • Chỉ hoạt động trên **Windows** (console host). Trên Linux/macOS (terminal) thường ném PlatformNotSupportedException hoặc trả về giá trị cố định.
  • Giá trị phụ thuộc vào font console và độ phân giải màn hình.
  • Buffer size phải >= Window size. Thường set Buffer trước rồi mới Window.
  • Không dùng cho ứng dụng GUI/Web.