Console.ReadKey Método

Definición

Obtiene la siguiente tecla de carácter o de función presionada por el usuario.

Sobrecargas

ReadKey()

Obtiene la siguiente tecla de carácter o de función presionada por el usuario. La tecla presionada se muestra en la ventana de la consola.

ReadKey(Boolean)

Obtiene la siguiente tecla de carácter o de función presionada por el usuario. Opcionalmente, la tecla presionada se muestra en la ventana de la consola.

ReadKey()

Obtiene la siguiente tecla de carácter o de función presionada por el usuario. La tecla presionada se muestra en la ventana de la consola.

public:
 static ConsoleKeyInfo ReadKey();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static ConsoleKeyInfo ReadKey ();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static ConsoleKeyInfo ReadKey ();
public static ConsoleKeyInfo ReadKey ();
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadKey : unit -> ConsoleKeyInfo
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
static member ReadKey : unit -> ConsoleKeyInfo
static member ReadKey : unit -> ConsoleKeyInfo
Public Shared Function ReadKey () As ConsoleKeyInfo

Devoluciones

Objeto que describe la constante ConsoleKey y el carácter Unicode, si existe, que corresponden a la tecla presionada de la consola. El objeto ConsoleKeyInfo también describe, en una combinación bit a bit de valores de ConsoleModifiers, si alguna de las teclas modificadoras Mayús, Alt o Ctrl se presionaron al mismo tiempo que la tecla de la consola.

Atributos

Excepciones

La propiedad In se ha redirigido desde alguna otra secuencia distinta de la consola.

Ejemplos

Uno de los usos más comunes del método es detener la ReadKey() ejecución del programa hasta que el usuario presiona una tecla y la aplicación finaliza o muestra una ventana adicional de información. En el ejemplo siguiente se usa el ReadKey() método para esperar a que el usuario presione la tecla Entrar antes de finalizar la aplicación.

using System;

public class Example
{
   public static void Main()
   {
      DateTime dat = DateTime.Now;
      Console.WriteLine("The time: {0:d} at {0:t}", dat);
      TimeZoneInfo tz = TimeZoneInfo.Local;
      Console.WriteLine("The time zone: {0}\n",
                        tz.IsDaylightSavingTime(dat) ?
                           tz.DaylightName : tz.StandardName);
      Console.Write("Press <Enter> to exit... ");
      while (Console.ReadKey().Key != ConsoleKey.Enter) {}
   }
}
// The example displays output like the following:
//     The time: 11/11/2015 at 4:02 PM:
//     The time zone: Pacific Standard Time
open System

let dat = DateTime.Now
printfn $"The time: {dat:d} at {dat:t}"

let tz = TimeZoneInfo.Local
printfn $"The time zone: {if tz.IsDaylightSavingTime dat then tz.DaylightName else tz.StandardName}\n"
printf"Press <Enter> to exit... "
while Console.ReadKey().Key <> ConsoleKey.Enter do ()


// The example displays output like the following:
//     The time: 12/28/2021 at 8:35 PM
//     The time zone: Pacific Standard Time
Module Example
   Public Sub Main()
      Dim dat As Date = Date.Now
      Console.WriteLine("The time: {0:d} at {0:t}", dat)
      Dim tz As TimeZoneInfo = TimeZoneInfo.Local
      Console.WriteLine("The time zone: {0}", 
                        If(tz.IsDaylightSavingTime(dat),
                           tz.DaylightName, tz.StandardName))
      Console.WriteLine()
      Console.Write("Press <Enter> to exit... ")
      Do While Console.ReadKey().Key <> ConsoleKey.Enter
      Loop
   End Sub
End Module
' The example displays the following output:
'     The time: 11/11/2015 at 4:02 PM
'     The time zone: Pacific Standard Time

Tenga en cuenta que esta sobrecarga del ReadKey método de forma predeterminada devuelve las teclas que el usuario presiona en la consola. Para suprimirlos, llame al ReadKey método con un intercept argumento de true.

En el ejemplo siguiente se usa el ReadKey() método para mostrar información sobre qué tecla presionó el usuario.

using namespace System;

void main()
{
   ConsoleKeyInfo cki;
   // Prevent example from ending if CTL+C is pressed.
   Console::TreatControlCAsInput = true;

   Console::WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
   Console::WriteLine("Press the Escape (Esc) key to quit: \n");
   do 
   {
      cki = Console::ReadKey();
      Console::Write(" --- You pressed ");
      if((cki.Modifiers & ConsoleModifiers::Alt) != ConsoleModifiers()) Console::Write("ALT+");
      if((cki.Modifiers & ConsoleModifiers::Shift) != ConsoleModifiers()) Console::Write("SHIFT+");
      if((cki.Modifiers & ConsoleModifiers::Control) != ConsoleModifiers()) Console::Write("CTL+");
      Console::WriteLine(cki.Key.ToString());
   } while (cki.Key != ConsoleKey::Escape);
}
// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//       
//       a --- You pressed A 
//       k --- You pressed ALT+K 
//       ► --- You pressed CTL+P 
//         --- You pressed RightArrow 
//       R --- You pressed SHIFT+R 
//                --- You pressed CTL+I 
//       j --- You pressed ALT+J 
//       O --- You pressed SHIFT+O 
//       § --- You pressed CTL+U }
using System;

class Example
{
   public static void Main()
   {
      ConsoleKeyInfo cki;
      // Prevent example from ending if CTL+C is pressed.
      Console.TreatControlCAsInput = true;

      Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
      Console.WriteLine("Press the Escape (Esc) key to quit: \n");
      do
      {
         cki = Console.ReadKey();
         Console.Write(" --- You pressed ");
         if((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
         if((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
         if((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
         Console.WriteLine(cki.Key.ToString());
       } while (cki.Key != ConsoleKey.Escape);
    }
}
// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//
//       a --- You pressed A
//       k --- You pressed ALT+K
//       ► --- You pressed CTL+P
//         --- You pressed RightArrow
//       R --- You pressed SHIFT+R
//                --- You pressed CTL+I
//       j --- You pressed ALT+J
//       O --- You pressed SHIFT+O
//       § --- You pressed CTL+U
open System

// Prevent example from ending if CTL+C is pressed.
Console.TreatControlCAsInput <- true

printfn "Press any combination of CTL, ALT, and SHIFT, and a console key."
printfn "Press the Escape (Esc) key to quit: \n"

let mutable cki = Unchecked.defaultof<ConsoleKeyInfo>

while cki.Key <> ConsoleKey.Escape do
    cki <- Console.ReadKey()
    printf " --- You pressed "
    if int (cki.Modifiers &&& ConsoleModifiers.Alt) <> 0 then printf "ALT+"
    if int (cki.Modifiers &&& ConsoleModifiers.Shift) <> 0 then printf "SHIFT+"
    if int (cki.Modifiers &&& ConsoleModifiers.Control) <> 0 then printf "CTL+"
    printfn $"{cki.Key}"


// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//
//       a --- You pressed A
//       k --- You pressed ALT+K
//       ► --- You pressed CTL+P
//         --- You pressed RightArrow
//       R --- You pressed SHIFT+R
//                --- You pressed CTL+I
//       j --- You pressed ALT+J
//       O --- You pressed SHIFT+O
//       § --- You pressed CTL+U
Class Example
   Public Shared Sub Main()
      Dim cki As ConsoleKeyInfo
      ' Prevent example from ending if CTL+C is pressed.
      Console.TreatControlCAsInput = True

      Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.")
      Console.WriteLine("Press the Escape (Esc) key to quit: " + vbCrLf)
      Do
         cki = Console.ReadKey()
         Console.Write(" --- You pressed ")
         If (cki.Modifiers And ConsoleModifiers.Alt) <> 0 Then Console.Write("ALT+")
         If (cki.Modifiers And ConsoleModifiers.Shift) <> 0 Then Console.Write("SHIFT+")
         If (cki.Modifiers And ConsoleModifiers.Control) <> 0 Then Console.Write("CTL+")
         Console.WriteLine(cki.Key.ToString)
      Loop While cki.Key <> ConsoleKey.Escape
   End Sub 
End Class 
' This example displays output similar to the following:
'       Press any combination of CTL, ALT, and SHIFT, and a console key.
'       Press the Escape (Esc) key to quit:
'       
'       a --- You pressed A 
'       k --- You pressed ALT+K 
'       ► --- You pressed CTL+P 
'         --- You pressed RightArrow 
'       R --- You pressed SHIFT+R 
'                --- You pressed CTL+I 
'       j --- You pressed ALT+J 
'       O --- You pressed SHIFT+O 
'       § --- You pressed CTL+U

Comentarios

El ReadKey método espera, es decir, se bloquea en el subproceso que emite el ReadKey método hasta que se presiona un carácter o una tecla de función. Se puede presionar un carácter o una tecla de función en combinación con una o varias teclas modificadoras Alt, Ctrl o Mayús. Sin embargo, al presionar una tecla modificadora por sí misma, el método no hará que se devuelva el ReadKey método.

En función de la aplicación, es posible que desee usar el ReadKey método junto con la KeyAvailable propiedad .

El ReadKey método lee desde el teclado incluso si la entrada estándar se redirige a un archivo con el SetIn método .

Consulte también

Se aplica a

ReadKey(Boolean)

Obtiene la siguiente tecla de carácter o de función presionada por el usuario. Opcionalmente, la tecla presionada se muestra en la ventana de la consola.

public:
 static ConsoleKeyInfo ReadKey(bool intercept);
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static ConsoleKeyInfo ReadKey (bool intercept);
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static ConsoleKeyInfo ReadKey (bool intercept);
public static ConsoleKeyInfo ReadKey (bool intercept);
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadKey : bool -> ConsoleKeyInfo
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
static member ReadKey : bool -> ConsoleKeyInfo
static member ReadKey : bool -> ConsoleKeyInfo
Public Shared Function ReadKey (intercept As Boolean) As ConsoleKeyInfo

Parámetros

intercept
Boolean

Determina si la tecla presionada se muestra en la ventana de la consola. true para que no se muestre la tecla presionada; de lo contrario, false.

Devoluciones

Objeto que describe la constante ConsoleKey y el carácter Unicode, si existe, que corresponden a la tecla presionada de la consola. El objeto ConsoleKeyInfo también describe, en una combinación bit a bit de valores de ConsoleModifiers, si alguna de las teclas modificadoras Mayús, Alt o Ctrl se presionaron al mismo tiempo que la tecla de la consola.

Atributos

Excepciones

La propiedad In se ha redirigido desde alguna otra secuencia distinta de la consola.

Ejemplos

Uno de los usos más comunes del método es detener la ReadKey ejecución del programa hasta que el usuario presiona una tecla y la aplicación finaliza o muestra una ventana adicional de información. En el ejemplo siguiente se usa el ReadKey(Boolean) método para esperar a que el usuario presione la tecla Entrar antes de finalizar la aplicación. Tenga en cuenta que, si el usuario presiona cualquier otra tecla, no se repite en la consola.

using System;

public class Example
{
   public static void Main()
   {
      DateTime dat = DateTime.Now;
      Console.WriteLine("The time: {0:d} at {0:t}", dat);
      TimeZoneInfo tz = TimeZoneInfo.Local;
      Console.WriteLine("The time zone: {0}\n",
                        tz.IsDaylightSavingTime(dat) ?
                           tz.DaylightName : tz.StandardName);
      Console.Write("Press <Enter> to exit... ");
      while (Console.ReadKey(true).Key != ConsoleKey.Enter) {}
   }
}
// The example displays output like the following:
//     The time: 11/11/2015 at 4:02 PM:
//     The time zone: Pacific Standard Time
open System

let dat = DateTime.Now
printfn $"The time: {dat:d} at {dat:t}"

let tz = TimeZoneInfo.Local
printfn $"The time zone: {if tz.IsDaylightSavingTime dat then tz.DaylightName else tz.StandardName}\n"
printf"Press <Enter> to exit... "
while Console.ReadKey(true).Key <> ConsoleKey.Enter do ()


// The example displays output like the following:
//     The time: 12/28/2021 at 8:37 PM
//     The time zone: Pacific Standard Time
Module Example
   Public Sub Main()
      Dim dat As Date = Date.Now
      Console.WriteLine("The time: {0:d} at {0:t}", dat)
      Dim tz As TimeZoneInfo = TimeZoneInfo.Local
      Console.WriteLine("The time zone: {0}", 
                        If(tz.IsDaylightSavingTime(dat),
                           tz.DaylightName, tz.StandardName))
      Console.WriteLine()
      Console.Write("Press <Enter> to exit... ")
      Do While Console.ReadKey(True).Key <> ConsoleKey.Enter
      Loop
   End Sub
End Module
' The example displays the following output:
'     The time: 11/11/2015 at 4:02 PM
'     The time zone: Pacific Standard Time

En el ejemplo siguiente se usa el ReadKey(Boolean) método para mostrar información sobre la tecla presionada por un usuario sin volver a mostrar esa tecla en la consola.

using namespace System;

void main()
{
   ConsoleKeyInfo cki;
   // Prevent example from ending if CTL+C is pressed.
   Console::TreatControlCAsInput = true;

   Console::WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
   Console::WriteLine("Press the Escape (Esc) key to quit: \n");
   do {
      cki = Console::ReadKey(true);
      Console::Write("You pressed ");
      if ((cki.Modifiers & ConsoleModifiers::Alt) != ConsoleModifiers()) Console::Write("ALT+");
      if ((cki.Modifiers & ConsoleModifiers::Shift) != ConsoleModifiers()) Console::Write("SHIFT+");
      if ((cki.Modifiers & ConsoleModifiers::Control) != ConsoleModifiers()) Console::Write("CTL+");
      Console::WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar);
   } while (cki.Key != ConsoleKey::Escape);
}
// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//       
//       You pressed CTL+A (character '☺')
//       You pressed C (character 'c')
//       You pressed CTL+C (character '♥')
//       You pressed K (character 'k')
//       You pressed ALT+I (character 'i')
//       You pressed ALT+U (character 'u')
//       You pressed ALT+SHIFT+H (character 'H')
//       You pressed Escape (character '←')
using System;

class Example
{
   public static void Main()
   {
      ConsoleKeyInfo cki;
      // Prevent example from ending if CTL+C is pressed.
      Console.TreatControlCAsInput = true;

      Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
      Console.WriteLine("Press the Escape (Esc) key to quit: \n");
      do {
         cki = Console.ReadKey(true);
         Console.Write("You pressed ");
         if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
         if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
         if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
         Console.WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar);
      } while (cki.Key != ConsoleKey.Escape);
   }
}
// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//
//       You pressed CTL+A (character '☺')
//       You pressed C (character 'c')
//       You pressed CTL+C (character '♥')
//       You pressed K (character 'k')
//       You pressed ALT+I (character 'i')
//       You pressed ALT+U (character 'u')
//       You pressed ALT+SHIFT+H (character 'H')
//       You pressed Escape (character '←')
open System

// Prevent example from ending if CTL+C is pressed.
Console.TreatControlCAsInput <- true

printfn "Press any combination of CTL, ALT, and SHIFT, and a console key."
printfn "Press the Escape (Esc) key to quit: \n"

let mutable cki = Unchecked.defaultof<ConsoleKeyInfo>

while cki.Key <> ConsoleKey.Escape do
    cki <- Console.ReadKey true
    printf "You pressed "
    if int (cki.Modifiers &&& ConsoleModifiers.Alt) <> 0 then printf "ALT+"
    if int (cki.Modifiers &&& ConsoleModifiers.Shift) <> 0 then printf "SHIFT+"
    if int (cki.Modifiers &&& ConsoleModifiers.Control) <> 0 then printf "CTL+"
    printfn $"{cki.Key} (character '{cki.KeyChar}')" 


// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//
//       You pressed CTL+A (character '☺')
//       You pressed C (character 'c')
//       You pressed CTL+C (character '♥')
//       You pressed K (character 'k')
//       You pressed ALT+I (character 'i')
//       You pressed ALT+U (character 'u')
//       You pressed ALT+SHIFT+H (character 'H')
//       You pressed Escape (character '←')
Class Example
   Public Shared Sub Main()
      Dim cki As ConsoleKeyInfo
      ' Prevent example from ending if CTL+C is pressed.
      Console.TreatControlCAsInput = True

      Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.")
      Console.WriteLine("Press the Escape (Esc) key to quit: " + vbCrLf)
      Do
         cki = Console.ReadKey(True)
         Console.Write("You pressed ")
         If (cki.Modifiers And ConsoleModifiers.Alt) <> 0 Then Console.Write("ALT+")
         If (cki.Modifiers And ConsoleModifiers.Shift) <> 0 Then Console.Write("SHIFT+")
         If (cki.Modifiers And ConsoleModifiers.Control) <> 0 Then Console.Write("CTL+")
         Console.WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar)
      Loop While cki.Key <> ConsoleKey.Escape
   End Sub
End Class 
' This example displays output similar to the following:
'       Press any combination of CTL, ALT, and SHIFT, and a console key.
'       Press the Escape (Esc) key to quit:
'       
'       You pressed CTL+A (character '☺')
'       You pressed C (character 'c')
'       You pressed CTL+C (character '♥')
'       You pressed K (character 'k')
'       You pressed ALT+I (character 'i')
'       You pressed ALT+U (character 'u')
'       You pressed ALT+SHIFT+H (character 'H')
'       You pressed Escape (character '←')

Comentarios

El ReadKey método espera, es decir, se bloquea en el subproceso que emite el ReadKey método hasta que se presiona un carácter o una tecla de función. Se puede presionar un carácter o una tecla de función en combinación con una o varias teclas modificadoras Alt, Ctrl o Mayús. Sin embargo, al presionar una tecla modificadora por sí misma, el método no hará que se devuelva el ReadKey método.

Si el intercept parámetro es true, se intercepta la tecla presionada y no se muestra en la ventana de la consola; de lo contrario, se muestra la tecla presionada.

En función de la aplicación, es posible que desee usar el ReadKey método junto con la KeyAvailable propiedad .

El ReadKey método lee desde el teclado incluso si la entrada estándar se redirige a un archivo con el SetIn método .

Consulte también

Se aplica a