Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle key press event in console application

I want to create a console application that will display the key that is pressed on the console screen, I made this code so far:

    static void Main(string[] args)     {         // this is absolutely wrong, but I hope you get what I mean         PreviewKeyDownEventArgs += new PreviewKeyDownEventArgs(keylogger);     }      private void keylogger(KeyEventArgs e)     {         Console.Write(e.KeyCode);     } 

I want to know, what should I type in main so I can call that event?

like image 853
R.Vector Avatar asked Jan 17 '12 16:01

R.Vector


People also ask

What is the use of console ReadKey ()?

ReadKey(Boolean)Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window.

How do I stop the ReadLine console?

This code sends [enter] into the current console process, aborting any ReadLine() calls blocking in unmanaged code deep within the windows kernel, which allows the C# thread to exit naturally.

What is ConsoleKeyInfo C#?

The ConsoleKeyInfo object describes the ConsoleKey constant and Unicode character, if any, that correspond to the pressed console key.

How do you pause a console application?

Try Ctrl + F5 in Visual Studio to run your program, this will add a pause with "Press any key to continue..." automatically without any Console.


1 Answers

For console application you can do this, the do while loop runs untill you press x

public class Program {     public static void Main()     {          ConsoleKeyInfo keyinfo;         do         {             keyinfo = Console.ReadKey();             Console.WriteLine(keyinfo.Key + " was pressed");         }         while (keyinfo.Key != ConsoleKey.X);     } } 

This will only work if your console application has focus. If you want to gather system wide key press events you can use windows hooks

like image 85
parapura rajkumar Avatar answered Sep 18 '22 00:09

parapura rajkumar