The problem is that the console is set, by default, to line input mode so
there is nothing in the input buffer until a line has been entered. The
solution is not to use a busy wait but to change the console input mode. The
following is a rough example:
Module Whatever
<System.Runtime.InteropServices.DllImport("kernel3 2")> _
Function SetConsoleMode(ByVal hConsoleHandle As IntPtr, _
ByVal dwMode As Integer) As Integer
End Function
<System.Runtime.InteropServices.DllImport("kernel3 2")> _
Function GetConsoleMode(ByVal hConsoleHandle As IntPtr, _
ByRef dwMode As Integer) As Integer
End Function
Private Const ENABLE_LINE_INPUT As Integer = 2
Private Const ENABLE_ECHO_INPUT As Integer = 4
Private Const CONIN As Integer = 3
Sub Main()
Dim hStdIn As New IntPtr(CONIN)
Dim nMode As Integer
Dim cInput As Char
GetConsoleMode(hStdIn, nMode)
nMode = (nMode And Not ENABLE_LINE_INPUT) _
And Not ENABLE_ECHO_INPUT
If SetConsoleMode(hStdIn, nMode) = 0 Then
'Error do something
Exit Sub
End If
Console.Write("Do you want to continue?(Y/N)")
Do While True
cInput = Char.ToUpper(Convert.ToChar(Console.Read()))
If cInput = "N"c Then
Exit Do
ElseIf cInput = "Y"c Then
Console.Write(cInput & vbCrLf)
Console.Write("Do you want to continue?(Y/N)")
End If
Loop
End Sub
End Module
"JM" <a@b.com> wrote in message
news:02****************************@phx.gbl...
Hi, thanks a lot for this code, I think I'll get there
with this.
But I only have a basic knowledge of C++ (have learned it
years ago but almost never used it), so I copied your
code into a new C++ .NET Class library, but when I try to
build the project, I get some errors and I don't know
what to do with it...
This is the build output:
------ Build started: Project: ConsoleHelpers,
Configuration: Debug Win32 ------
Compiling...
ConsoleHelpers.cpp
Linking...
ConsoleHelpers.obj : error LNK2001: unresolved external
symbol "int __cdecl _getch(void)" (?_getch@@$$J0YAHXZ)
ConsoleHelpers.obj : error LNK2001: unresolved external
symbol "int __cdecl _kbhit(void)" (?_kbhit@@$$J0YAHXZ)
D:\(...)\Visual Studio Projects\ConsoleApplication4
\Debug\ConsoleHelpers.dll : fatal error LNK1120: 2
unresolved externals
ConsoleHelpers - 3 error(s), 0 warning(s)
---------------------- Done ----------------------
Build: 0 succeeded, 1 failed, 0 skipped
BTW: my news server seems to be down so it might take a
little longer before I can react to any replies...
-----Original Message-----
(...)
You can't do it in straight VB.NET. All the console
functions waituntil ENTER has been pressed before stuff get's pushed
through thestreams.
There's a workaround, if you have Visual C++ .NET
Build the following VC++.NET Code and compile it:
#include "stdafx.h"
#include <conio.h>
namespace Helper
{
public __gc class InKey
{
public:
static System::Int32 ReadKeypress()
{
while ( ! _kbhit() ) {}
return _getch();
}
};
}
Then, reference the .NET DLL in your Console app and
call it likethis:
Dim nChar As Integer = Helper.InKey.ReadKeypress()
Hope that helps!
// CHRIS
.