다음을 통해 공유


Console.Clear 메서드

정의

콘솔 버퍼와 해당 콘솔 창에서 표시 정보를 지웁니다.

public:
 static void Clear();
public static void Clear ();
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static void Clear ();
static member Clear : unit -> unit
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
static member Clear : unit -> unit
Public Shared Sub Clear ()
특성

예외

I/O 오류가 발생했습니다.

예제

다음 예제 Clear 에서는 루프를 실행하기 전에 콘솔을 지우고 사용자에게 포그라운드 및 배경색을 선택하고 표시할 문자열을 입력하라는 메시지를 표시합니다. 사용자가 프로그램을 종료하지 않도록 선택하면 콘솔의 원래 전경색과 배경색이 복원되고 Clear 루프를 다시 실행하기 전에 메서드가 다시 호출됩니다.

using System;

public class Example
{
   public static void Main()
   {
      // Save colors so they can be restored when use finishes input.
      ConsoleColor dftForeColor = Console.ForegroundColor;
      ConsoleColor dftBackColor = Console.BackgroundColor;
      bool continueFlag = true;
      Console.Clear();

      do {
         ConsoleColor newForeColor = ConsoleColor.White;
         ConsoleColor newBackColor = ConsoleColor.Black;

         Char foreColorSelection = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ",
                                              new Char[] { 'B', 'R', 'Y' } );
         switch (foreColorSelection) {
            case 'B':
            case 'b':
               newForeColor = ConsoleColor.DarkBlue;
               break;
            case 'R':
            case 'r':
               newForeColor = ConsoleColor.DarkRed;
               break;
            case 'Y':
            case 'y':
               newForeColor = ConsoleColor.DarkYellow;
               break;
         }
         Char backColorSelection = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ",
                                              new Char[] { 'W', 'G', 'M' });
         switch (backColorSelection) {
            case 'W':
            case 'w':
               newBackColor = ConsoleColor.White;
               break;
            case 'G':
            case 'g':
               newBackColor = ConsoleColor.Green;
               break;
            case 'M':
            case 'm':
               newBackColor = ConsoleColor.Magenta;
               break;
         }

         Console.WriteLine();
         Console.Write("Enter a message to display: ");
         String textToDisplay = Console.ReadLine();
         Console.WriteLine();
         Console.ForegroundColor = newForeColor;
         Console.BackgroundColor = newBackColor;
         Console.WriteLine(textToDisplay);
         Console.WriteLine();
         if (Char.ToUpper(GetKeyPress("Display another message (Y/N): ", new Char[] { 'Y', 'N' } )) == 'N')
            continueFlag = false;

         // Restore the default settings and clear the screen.
         Console.ForegroundColor = dftForeColor;
         Console.BackgroundColor = dftBackColor;
         Console.Clear();
      } while (continueFlag);
   }

   private static Char GetKeyPress(String msg, Char[] validChars)
   {
      ConsoleKeyInfo keyPressed;
      bool valid = false;

      Console.WriteLine();
      do {
         Console.Write(msg);
         keyPressed = Console.ReadKey();
         Console.WriteLine();
         if (Array.Exists(validChars, ch => ch.Equals(Char.ToUpper(keyPressed.KeyChar))))
            valid = true;
      } while (! valid);
      return keyPressed.KeyChar;
   }
}
open System

let getKeyPress msg validChars =
    Console.WriteLine()
    
    let mutable valid = false
    let mutable keyChar = ' '
    
    while not valid do
        printfn "%s" msg
        let keyPressed = Console.ReadKey()
        printfn ""
        if validChars |> List.exists (fun ch -> ch.Equals(Char.ToUpper keyPressed.KeyChar)) then
            valid <- true
            keyChar <- keyPressed.KeyChar
    keyChar

// Save colors so they can be restored when use finishes input.
let dftForeColor = Console.ForegroundColor
let dftBackColor = Console.BackgroundColor
let mutable continueFlag = true
Console.Clear()

while continueFlag do
    let foreColorSelection = 
        getKeyPress "Select Text Color (B for Blue, R for Red, Y for Yellow): " [ 'B'; 'R'; 'Y' ]
    
    let newForeColor = 
        match foreColorSelection with
        | 'B' | 'b' ->
            ConsoleColor.DarkBlue
        | 'R' | 'r' ->
            ConsoleColor.DarkRed
        | 'Y' | 'y' ->
            ConsoleColor.DarkYellow
        | _ -> ConsoleColor.White

    let backColorSelection = 
        getKeyPress "Select Background Color (W for White, G for Green, M for Magenta): " [ 'W'; 'G'; 'M' ]

    let newBackColor = 
        match backColorSelection with
        | 'W' | 'w' ->
            ConsoleColor.White
        | 'G' | 'g' ->
            ConsoleColor.Green
        | 'M' | 'm' ->
            ConsoleColor.Magenta
        | _ -> ConsoleColor.Black

    printfn ""
    printf "Enter a message to display: "
    let textToDisplay = Console.ReadLine()
    printfn ""
    Console.ForegroundColor <- newForeColor
    Console.BackgroundColor <- newBackColor
    printfn "%s" textToDisplay
    printfn ""
    if Char.ToUpper(getKeyPress "Display another message (Y/N): " [ 'Y'; 'N' ] ) = 'N' then
        continueFlag <- false

    // Restore the default settings and clear the screen.
    Console.ForegroundColor <- dftForeColor
    Console.BackgroundColor <- dftBackColor
    Console.Clear()
Module Example
   Public Sub Main()
      ' Save colors so they can be restored when use finishes input.
      Dim dftForeColor As ConsoleColor = Console.ForegroundColor
      Dim dftBackColor As ConsoleColor = Console.BackgroundColor
      Dim continueFlag As Boolean = True
      Console.Clear()
            
      Do 
         Dim newForeColor As ConsoleColor
         Dim newBackColor As ConsoleColor
                  
         Dim foreColorSelection As Char = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ", 
                                              { "B"c, "R"c, "Y"c } )
         Select Case foreColorSelection
            Case "B"c, "b"c
               newForeColor = ConsoleColor.DarkBlue
            Case "R"c, "r"c
               newForeColor = ConsoleColor.DarkRed
            Case "Y"c, "y"c
               newForeColor = ConsoleColor.DarkYellow   
         End Select
         Dim backColorSelection As Char = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ",
                                              { "W"c, "G"c, "M"c })
         Select Case backColorSelection
            Case "W"c, "w"c
               newBackColor = ConsoleColor.White
            Case "G"c, "g"c
               newBackColor = ConsoleColor.Green
            Case "M"c, "m"c
               newBackColor = ConsoleColor.Magenta   
         End Select
         
         Console.WriteLine()
         Console.Write("Enter a message to display: ")
         Dim textToDisplay As String = Console.ReadLine()
         Console.WriteLine()
         Console.ForegroundColor = newForeColor
         Console.BackgroundColor = newBackColor
         Console.WriteLine(textToDisplay)
         Console.WriteLine()
         If Char.ToUpper(GetKeyPress("Display another message (Y/N): ", { "Y"c, "N"c } )) = "N" Then
            continueFlag = False
         End If
         ' Restore the default settings and clear the screen.
         Console.ForegroundColor = dftForeColor
         Console.BackgroundColor = dftBackColor
         Console.Clear()
      Loop While continueFlag
   End Sub
   
   Private Function GetKeyPress(msg As String, validChars() As Char) As Char
      Dim keyPressed As ConsoleKeyInfo
      Dim valid As Boolean = False
      
      Console.WriteLine()
      Do
         Console.Write(msg)
         keyPressed = Console.ReadKey()
         Console.WriteLine()
         If Array.Exists(validChars, Function(ch As Char) ch.Equals(Char.ToUpper(keypressed.KeyChar)))           
            valid = True
         End If
      Loop While Not valid
      Return keyPressed.KeyChar 
   End Function
End Module

이 예제에서는 사용자가 포그라운드 및 배경색을 선택하는지 유효성을 검사하는 메서드를 사용합니다 GetKeyPress .

이 예제에서는 CursorLeft 속성 및 CursorTop 메서드와 SetCursorPosition Clear 속성을 보여 줍니다. 이 예제에서는 "+", "|" 및 "-" 문자열의 조합을 사용하여 5자 x 5자 직사각형을 그리기 위해 다음 쓰기가 발생할 위치를 결정하는 커서를 배치합니다. 다른 문자열의 조합을 사용하여 더 적은 수의 단계로 사각형을 그릴 수 있습니다.

// This example demonstrates the 
//     Console.CursorLeft and 
//     Console.CursorTop properties, and the
//     Console.SetCursorPosition and 
//     Console.Clear methods.
using namespace System;
int origRow;
int origCol;
void WriteAt( String^ s, int x, int y )
{
   try
   {
      Console::SetCursorPosition( origCol + x, origRow + y );
      Console::Write( s );
   }
   catch ( ArgumentOutOfRangeException^ e ) 
   {
      Console::Clear();
      Console::WriteLine( e->Message );
   }

}

int main()
{
   
   // Clear the screen, then save the top and left coordinates.
   Console::Clear();
   origRow = Console::CursorTop;
   origCol = Console::CursorLeft;
   
   // Draw the left side of a 5x5 rectangle, from top to bottom.
   WriteAt( "+", 0, 0 );
   WriteAt( "|", 0, 1 );
   WriteAt( "|", 0, 2 );
   WriteAt( "|", 0, 3 );
   WriteAt( "+", 0, 4 );
   
   // Draw the bottom side, from left to right.
   WriteAt( "-", 1, 4 ); // shortcut: WriteAt("---", 1, 4)
   WriteAt( "-", 2, 4 ); // ...
   WriteAt( "-", 3, 4 ); // ...
   WriteAt( "+", 4, 4 );
   
   // Draw the right side, from bottom to top.
   WriteAt( "|", 4, 3 );
   WriteAt( "|", 4, 2 );
   WriteAt( "|", 4, 1 );
   WriteAt( "+", 4, 0 );
   
   // Draw the top side, from right to left.
   WriteAt( "-", 3, 0 ); // shortcut: WriteAt("---", 1, 0)
   WriteAt( "-", 2, 0 ); // ...
   WriteAt( "-", 1, 0 ); // ...
   
   //
   WriteAt( "All done!", 0, 6 );
   Console::WriteLine();
}

/*
This example produces the following results:

+---+
|   |
|   |
|   |
+---+

All done!

*/
// This example demonstrates the
//     Console.CursorLeft and
//     Console.CursorTop properties, and the
//     Console.SetCursorPosition and
//     Console.Clear methods.
using System;

class Sample
{
    protected static int origRow;
    protected static int origCol;

    protected static void WriteAt(string s, int x, int y)
    {
    try
        {
        Console.SetCursorPosition(origCol+x, origRow+y);
        Console.Write(s);
        }
    catch (ArgumentOutOfRangeException e)
        {
        Console.Clear();
        Console.WriteLine(e.Message);
        }
    }

    public static void Main()
    {
// Clear the screen, then save the top and left coordinates.
    Console.Clear();
    origRow = Console.CursorTop;
    origCol = Console.CursorLeft;

// Draw the left side of a 5x5 rectangle, from top to bottom.
    WriteAt("+", 0, 0);
    WriteAt("|", 0, 1);
    WriteAt("|", 0, 2);
    WriteAt("|", 0, 3);
    WriteAt("+", 0, 4);

// Draw the bottom side, from left to right.
    WriteAt("-", 1, 4); // shortcut: WriteAt("---", 1, 4)
    WriteAt("-", 2, 4); // ...
    WriteAt("-", 3, 4); // ...
    WriteAt("+", 4, 4);

// Draw the right side, from bottom to top.
    WriteAt("|", 4, 3);
    WriteAt("|", 4, 2);
    WriteAt("|", 4, 1);
    WriteAt("+", 4, 0);

// Draw the top side, from right to left.
    WriteAt("-", 3, 0); // shortcut: WriteAt("---", 1, 0)
    WriteAt("-", 2, 0); // ...
    WriteAt("-", 1, 0); // ...
//
    WriteAt("All done!", 0, 6);
    Console.WriteLine();
    }
}
/*
This example produces the following results:

+---+
|   |
|   |
|   |
+---+

All done!

*/
// This example demonstrates the
//     Console.CursorLeft and
//     Console.CursorTop properties, and the
//     Console.SetCursorPosition and
//     Console.Clear methods.
open System

// Clear the screen, then save the top and left coordinates.
Console.Clear()
let origRow = Console.CursorTop
let origCol = Console.CursorLeft

let writeAt s x y =
    try
        Console.SetCursorPosition(origCol + x, origRow + y)
        printfn $"%s{s}"
    with :? ArgumentOutOfRangeException as e ->
        Console.Clear()
        printfn $"{e.Message}"

// Draw the left side of a 5x5 rectangle, from top to bottom.
writeAt "+" 0 0
writeAt "|" 0 1
writeAt "|" 0 2
writeAt "|" 0 3
writeAt "+" 0 4

// Draw the bottom side, from left to right.
writeAt "-" 1 4 // shortcut: writeAt "---", 1, 4)
writeAt "-" 2 4 // ...
writeAt "-" 3 4 // ...
writeAt "+" 4 4

// Draw the right side, from bottom to top.
writeAt "|" 4 3
writeAt "|" 4 2
writeAt "|" 4 1
writeAt "+" 4 0

// Draw the top side, from right to left.
writeAt "-" 3 0 // shortcut: writeAt "---", 1, 0)
writeAt "-" 2 0 // ...
writeAt "-" 1 0 // ...

writeAt "All done!" 0 6
printfn ""


// This example produces the following results:
//
// +---+
// |   |
// |   |
// |   |
// +---+
//
// All done!
' This example demonstrates the 
'     Console.CursorLeft and 
'     Console.CursorTop properties, and the
'     Console.SetCursorPosition and 
'     Console.Clear methods.
Class Sample
   Protected Shared origRow As Integer
   Protected Shared origCol As Integer
   
   Protected Shared Sub WriteAt(s As String, x As Integer, y As Integer)
      Try
         Console.SetCursorPosition(origCol + x, origRow + y)
         Console.Write(s)
      Catch e As ArgumentOutOfRangeException
         Console.Clear()
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Public Shared Sub Main()
      ' Clear the screen, then save the top and left coordinates.
      Console.Clear()
      origRow = Console.CursorTop
      origCol = Console.CursorLeft
      
      ' Draw the left side of a 5x5 rectangle, from top to bottom.
      WriteAt("+", 0, 0)
      WriteAt("|", 0, 1)
      WriteAt("|", 0, 2)
      WriteAt("|", 0, 3)
      WriteAt("+", 0, 4)
      
      ' Draw the bottom side, from left to right.
      WriteAt("-", 1, 4) ' shortcut: WriteAt("---", 1, 4)
      WriteAt("-", 2, 4) ' ...
      WriteAt("-", 3, 4) ' ...
      WriteAt("+", 4, 4)
      
      ' Draw the right side, from bottom to top.
      WriteAt("|", 4, 3)
      WriteAt("|", 4, 2)
      WriteAt("|", 4, 1)
      WriteAt("+", 4, 0)
      
      ' Draw the top side, from right to left.
      WriteAt("-", 3, 0) ' shortcut: WriteAt("---", 1, 0)
      WriteAt("-", 2, 0) ' ...
      WriteAt("-", 1, 0) ' ...
      '
      WriteAt("All done!", 0, 6)
      Console.WriteLine()
   End Sub
End Class
'
'This example produces the following results:
'
'+---+
'|   |
'|   |
'|   |
'+---+
'
'All done!
'

설명

이 메서드를 Clear 사용하는 것은 명령 프롬프트 창에서 MS-DOS cls 명령을 호출하는 것과 동일합니다. 메서드가 Clear 호출되면 커서가 창의 왼쪽 위 모서리로 자동으로 스크롤되고 화면 버퍼의 내용이 현재 전경 배경색을 사용하여 공백으로 설정됩니다.

참고

호출을 시도 합니다 Clear 메서드는 콘솔 애플리케이션의 출력을 파일로 리디렉션되는 경우 throw를 IOException입니다. 이를 방지하려면 항상 메서드에 대한 호출을 Clear ...로 try래핑합니다.catch 블록.

적용 대상