Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Console Input Question

66 views
Skip to first unread message

Paul Giller

unread,
Sep 25, 2001, 5:01:13 PM9/25/01
to
I'm scratching my head right now, because I can't find an equivalent to the
_getch() c run time library function. Both Console.Read() and
Console.ReadLine() require carriage returns before they return. I want to
read a single character entry without the user hiting return. Is there no
such facility within the .NET framework to do this?


Willy Denoyette

unread,
Sep 26, 2001, 5:41:05 AM9/26/01
to
No, there isn't, but you can allways use P/Invoke to switch the console from line mode to character mode.

using System;
using System.Runtime.InteropServices;

public class Con {
const int STD_INPUT_HANDLE = -10;
const int ENABLE_LINE_INPUT = 0x0002;
const int ENABLE_ECHO_INPUT = 0x0004;
[DllImport("kernel32")]
public static extern IntPtr GetStdHandle( int nStdHandle);
[DllImport("kernel32")]
public static extern bool GetConsoleMode( IntPtr hConsoleHandle, ref int pmode);
[DllImport("kernel32")]
public static extern bool SetConsoleMode( IntPtr hConsoleHandle, int mode);
public static void EnableCharMode() {
IntPtr hConsole;
int mode= 0;
hConsole = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hConsole, ref mode);

// must turn off echo mode when character input
mode &= ~ (ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
SetConsoleMode(hConsole, mode)
}

public static void EnableLineMode() {
IntPtr hConsole;
int mode=0;
hConsole = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hConsole, ref mode);
mode |= (ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
SetConsoleMode(hConsole, mode)
}

Create an instance of the class and call EnableCharMode when single char input is required, dont forget to reset the console to
linemode before terminating the program.

Willy.
"Paul Giller" <Pa...@InnerCOM.co.uk> wrote in message news:OT0bNimRBHA.1544@tkmsftngp05...

Peter Torr (MS)

unread,
Sep 29, 2001, 6:21:31 PM9/29/01
to
"Willy Denoyette" <willy.d...@pandora.be> wrote in message
news:#dVRo$mRBHA.2132@tkmsftngp05...

> No, there isn't, but you can allways use P/Invoke to switch the console
from line mode to character mode.

Cool; you can also create a Managed C++ class with a single method that
calls _getch() for you. It's probably also useful to have _kbhit() in there:

#using <mscorlib.dll>
#include <conio.h>
namespace Utils
{
public __gc class Keyboard
{
public:
static System::Int32 GetKey()
{
if (_kbhit())
return _getch();
else
return -1;
}
};
}


Compile with:

cl /clr /LD filename.cpp

Peter

--
Peter Torr -- pt...@microsoft.com -- JScript .NET / VSA Runtime
Waiting for the Vengabus? http://www.microsoft.com/info/cpyright.htm
Please post all questions to the group. Thanks.

0 new messages