non blocking console read

  • Thread starter Thread starter Richard Bell
  • Start date Start date
R

Richard Bell

Is there a way to do a non-blocking console read in VB.net? Something
a bit like the old INKEY$?
 
Is there a way to do a non-blocking console read in VB.net? Something
a bit like the old INKEY$?

You can use P/Invoke to call the SetConsoleMode API to change the input
modes...
 
Thanks Tom.

With your clue and a quick Google I found a great example.

Regards,
Richard

public class PwdConsole {
[DllImport("kernel32", SetLastError=true)]
static extern IntPtr GetStdHandle(IntPtr whichHandle);
[DllImport("kernel32", SetLastError=true)]
static extern bool GetConsoleMode(IntPtr handle, out uint mode);
[DllImport("kernel32", SetLastError=true)]
static extern bool SetConsoleMode(IntPtr handle, uint mode);

static readonly IntPtr STD_INPUT_HANDLE = new IntPtr(-10);
const int ENABLE_LINE_INPUT = 2;
const uint ENABLE_ECHO_INPUT = 4;

public static string ReadLine() {
// turn off console echo
IntPtr hConsole = GetStdHandle(STD_INPUT_HANDLE);
uint oldMode;
if (!GetConsoleMode(hConsole, out oldMode)) {
throw new ApplicationException("GetConsoleMode failed");
}
uint newMode = oldMode & ~(ENABLE_LINE_INPUT |
ENABLE_ECHO_INPUT);
if (!SetConsoleMode(hConsole, newMode)) {
throw new ApplicationException("SetConsoleMode failed");
}
int i;
StringBuilder secret = new StringBuilder();
while (true) {
i = Console.Read ();
if (i == 13) // break when
break;
secret.Append((char) i);
Console.Write ("*");
}

Console.WriteLine();
// restore console echo and line input mode
if (!SetConsoleMode(hConsole, oldMode)) {
throw new ApplicationException("SetConsoleMode failed");
}
return secret.ToString();
}
}
 
Back
Top