简体   繁体   中英

C# visual basic express, how do i check if backspace or esc is pressed

I'm new to C# and am coding a basic console application with a main menu. When in a part of the program I'd like the user to be able to press backspace to be able to return to main menu or press ESC to quit the program.

How can I tell if the backspace and ESC are pressed?

I assume its not a simple as detected letters and numbers?

for example id like:

    // Press backspace to go back to main menu or press esc to exit program
    Console.WriteLine("Press BACKSPACE to return to main menu, or ESC to quit.");
    if(backspace.ispressed )
    {
      menuOption = Console.ReadLine();

    }else if(esc.ispressed){

      Environment.Exit(0)
    }

Asuming that you are in a WinForms environment you need to bind to a KeyDown event on a control. For example if you want to check it on a TextBox element you can do the following:

this.TextSearch.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextSearchKeyDown)
private void TextSearchKeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Escape)
     {
         // Do stuff
     }
}

look at this page on Console.ReadKey

Example:

var cki = Console.ReadKey();
if(cki.Key == ConsoleKey.Escape)
{
    Environment.Exit(0)
}
else if(if (cki.Key == ConsoleKey.Backspace)
{
    menuOption = Console.ReadLine();
}

Use Console.ReadKey() to detect the key being pressed

Console.WriteLine("Press BACKSPACE to return to main menu, or ESC to quit.");
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key == ConsoleKey.Backspace)
{
    menuOption = Console.ReadLine();

}else if (key.Key == ConsoleKey.Escape){

    Environment.Exit(0);
}

http://msdn.microsoft.com/en-us/library/471w8d85.aspx

The code here is using Console.ReadKey() to fill a key object and then checking the .key attribute against ConsoleKey.Escape

Documentation for ConsoleKey here: http://msdn.microsoft.com/en-us/library/system.consolekey.aspx

 ConsoleKeyInfo keyinfo;
 keyinfo = Console.ReadKey();
 if (keyinfo == Keys.Esc || keyinfo == keys.Backspace)

Should do it?

try this

if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
    // do something
}
if (Console.ReadKey(true).Key == ConsoleKey.Backspace)
{
    // do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM