C#, kbhit & getch

Status
Not open for further replies.

BobLewiston

In Runtime
Messages
182
In C#, what methods take the place of the old kbhit and getch functions in C? (I'm writing a console application in Visual Studio.)
 
Code:
Console.WriteLine("Press the X key to exit.");
Console.ReadLine();

Then after that you would validate what key was pressed.
 
attention, Baez:

No, I don't want:

1. the character entered to be echoed to screen until my application checks that it was one deemed to be a valid response,

2. to require the user to press the "Enter" key after entering the character constituting their response, and

3. to echo to screen the carriage return and line feed that "enter" entails.

Instead, I want to:

1. detect when any key has been pressed (kbhit), and then

2. retrieve the character entered from the keyboard buffer (getch).

Does anyone know the names of the classes and methods with these functionalities, and what Framework library ("using") files they're in?

Also, does anyone know how to toggle echo-to-screen, as was done in C (if I remember correctly) via system ("echo off") and system ("echo on")?
 
Take a look through all the static methods on the Console class. It is defined in the "System" namespace. Since you're using Visual Studio, use intellisense to look at the methods defined on the Console class. There are several, including Console.ReadKey(), which is what you seem to want.
 
You can use Interop to call _kbhit. The version of kbhit without the underscore is actually depricated. Make sure you use STAThread to ensure everything is synchronized; both COM and Windows objects.

Code:
using System;
using System.Runtime.InteropServices;

public class Win32Interop
{
   [DllImport("crtdll.dll")]
   public static extern int _kbhit();
}

class KBHIT
{
   [STAThread]
   static void Main(string[] args)
   {
      System.Console.WriteLine( "Press any key: " );
      while(!Win32Interop._kbhit());
   }
}
 
That code won't run. Actually, it won't compile because the negation operator cannot be applied to any type other than an object of type Boolean. In your case, you're applying it to an integer.

Anyhow, it's a bit overkill to use p-invoke when the Console class provides all the methods (ReadKey() in this case) that do the exact same thing.
 
Yeah was in a C++ mindset. Use while(Win32Interop._kbhit() == 0); instead. Just tested it in XP and it worked.
 
Status
Not open for further replies.
Back
Top Bottom