Console.ReadKey Console.ReadKey Console.ReadKey Console.ReadKey Method

Definición

Obtiene la siguiente tecla de carácter o de función presionada por el usuario.Obtains the next character or function key pressed by the user.

Sobrecargas

ReadKey() ReadKey() ReadKey() ReadKey()

Obtiene la siguiente tecla de carácter o de función presionada por el usuario.Obtains the next character or function key pressed by the user. La tecla presionada se muestra en la ventana de la consola.The pressed key is displayed in the console window.

ReadKey(Boolean) ReadKey(Boolean) ReadKey(Boolean) ReadKey(Boolean)

Obtiene la siguiente tecla de carácter o de función presionada por el usuario.Obtains the next character or function key pressed by the user. Opcionalmente, la tecla presionada se muestra en la ventana de la consola.The pressed key is optionally displayed in the console window.

ReadKey() ReadKey() ReadKey() ReadKey()

Obtiene la siguiente tecla de carácter o de función presionada por el usuario.Obtains the next character or function key pressed by the user. La tecla presionada se muestra en la ventana de la consola.The pressed key is displayed in the console window.

public:
 static ConsoleKeyInfo ReadKey();
public static ConsoleKeyInfo ReadKey ();
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.An object that describes the ConsoleKey constant and Unicode character, if any, that correspond to the pressed console key. 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.The ConsoleKeyInfo object also describes, in a bitwise combination of ConsoleModifiers values, whether one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously with the console key.

Excepciones

La propiedad In se ha redirigido desde alguna otra secuencia distinta de la consola.The In property is redirected from some stream other than the console.

Ejemplos

Uno de los usos más comunes del ReadKey() método es detener la ejecución del programa hasta que el usuario presione una tecla y la aplicación finalice o muestre una ventana de información adicional.One of the most common uses of the ReadKey() method is to halt program execution until the user presses a key and the app either terminates or displays an additional window of information. En el ejemplo siguiente se ReadKey() usa el método para esperar a que el usuario presione la tecla entrar antes de finalizar la aplicación.The following example uses the ReadKey() method to wait for the user to press the Enter key before terminating the app.

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
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 ReadKey del método repite de forma predeterminada cualquier clave que se pueda mostrar que el usuario presiona en la consola.Note that this overload of the ReadKey method by default echoes any displayable keys that the user presses to the console. Para suprimirlos, llame al ReadKey método con un intercept argumento de true.To suppress them, call the ReadKey method with an intercept argument of true.

En el ejemplo siguiente se ReadKey() usa el método para mostrar información sobre la tecla que presionó el usuario.The following example uses the ReadKey() method to display information about which key the user pressed.

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 
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, los bloques en el subproceso que emite ReadKey el método hasta que se presiona una tecla de carácter o de función.The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed. Una tecla de carácter o de función se puede presionar junto con una o varias teclas modificadoras Alt, Ctrl o Mayús.A character or function key can be pressed in combination with one or more Alt, Ctrl, or Shift modifier keys. Sin embargo, si se presiona una tecla modificadora por sí sola ReadKey , no se devolverá el método.However, pressing a modifier key by itself will not cause the ReadKey method to return.

Dependiendo de la aplicación, es posible que desee utilizar el ReadKey método junto con la KeyAvailable propiedad.Depending on your application, you might want to use the ReadKey method in conjunction with the KeyAvailable property.

El ReadKey método lee del teclado aunque la entrada estándar se redirija a un archivo con el SetIn método.The ReadKey method reads from the keyboard even if the standard input is redirected to a file with the SetIn method.

Consulte también:

ReadKey(Boolean) ReadKey(Boolean) ReadKey(Boolean) ReadKey(Boolean)

Obtiene la siguiente tecla de carácter o de función presionada por el usuario.Obtains the next character or function key pressed by the user. Opcionalmente, la tecla presionada se muestra en la ventana de la consola.The pressed key is optionally displayed in the console window.

public:
 static ConsoleKeyInfo ReadKey(bool intercept);
public static ConsoleKeyInfo ReadKey (bool intercept);
static member ReadKey : bool -> ConsoleKeyInfo
Public Shared Function ReadKey (intercept As Boolean) As ConsoleKeyInfo

Parámetros

intercept
Boolean Boolean Boolean Boolean

Determina si la tecla presionada se muestra en la ventana de la consola.Determines whether to display the pressed key in the console window. true para que no se muestre la tecla presionada; de lo contrario, false.true to not display the pressed key; otherwise, false.

Devoluciones

Objeto que describe la constante ConsoleKey y el carácter Unicode, si existe, que corresponden a la tecla presionada de la consola.An object that describes the ConsoleKey constant and Unicode character, if any, that correspond to the pressed console key. 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.The ConsoleKeyInfo object also describes, in a bitwise combination of ConsoleModifiers values, whether one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously with the console key.

Excepciones

La propiedad In se ha redirigido desde alguna otra secuencia distinta de la consola.The In property is redirected from some stream other than the console.

Ejemplos

Uno de los usos más comunes del ReadKey método es detener la ejecución del programa hasta que el usuario presione una tecla y la aplicación finalice o muestre una ventana de información adicional.One of the most common uses of the ReadKey method is to halt program execution until the user presses a key and the app either terminates or displays an additional window of information. En el ejemplo siguiente se ReadKey(Boolean) usa el método para esperar a que el usuario presione la tecla entrar antes de finalizar la aplicación.The following example uses the ReadKey(Boolean) method to wait for the user to press the Enter key before terminating the app. Tenga en cuenta que, si el usuario presiona cualquier otra tecla, no se mostrará en la consola.Note that, if the user presses any other key, it is not echoed to the console.

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
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 ReadKey(Boolean) usa el método para mostrar información sobre la tecla presionada por un usuario sin repetir esa clave en la consola.The following example uses the ReadKey(Boolean) method to display information about the key pressed by a user without echoing that key to the console.

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 '←')
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, los bloques en el subproceso que emite ReadKey el método hasta que se presiona una tecla de carácter o de función.The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed. Una tecla de carácter o de función se puede presionar junto con una o varias teclas modificadoras Alt, Ctrl o Mayús.A character or function key can be pressed in combination with one or more Alt, Ctrl, or Shift modifier keys. Sin embargo, si se presiona una tecla modificadora por sí sola ReadKey , no se devolverá el método.However, pressing a modifier key by itself will not cause the ReadKey method to return.

Si el intercept parámetro es true, la tecla presionada se intercepta y no se muestra en la ventana de la consola; de lo contrario, se muestra la tecla presionada.If the intercept parameter is true, the pressed key is intercepted and not displayed in the console window; otherwise, the pressed key is displayed.

Dependiendo de la aplicación, es posible que desee utilizar el ReadKey método junto con la KeyAvailable propiedad.Depending on your application, you might want to use the ReadKey method in conjunction with the KeyAvailable property.

El ReadKey método lee del teclado aunque la entrada estándar se redirija a un archivo con el SetIn método.The ReadKey method reads from the keyboard even if the standard input is redirected to a file with the SetIn method.

Consulte también:

Se aplica a