VB.net Console Application Problem

Soldato
Joined
9 Jan 2003
Posts
6,801
Location
Darlington
I am trying to understand how to detect a simple keypress while running a console application under vb.net.

In short I would like a loop to repeat continuously until a key press is detected at which point it would exit the loop.

I have this so far:

Module Module1
Private theKey As ConsoleKeyInfo = New ConsoleKeyInfo

Sub Main()

Do
'theKey = Console.ReadKey(True)
Select Case theKey.Key
Case ConsoleKey.Enter
Exit Do
Case Else
Console.WriteLine("Hello World")
End Select
Loop
End Sub

End Module


...but this requires a key press every iteration which is what I am trying to avoid, however the enter keypress does exit the loop so part of it is work.

Any ideas?

Egon
 
http://msdn.microsoft.com/en-us/library/system.console.keyavailable.aspx

PHP:
      Do
         Console.WriteLine(vbCrLf & "Press a key to display; press the 'x' key to quit.")

' Your code could perform some useful task in the following loop. However, 
' for the sake of this example we'll merely pause for a quarter second.

         While Console.KeyAvailable = False
            Thread.Sleep(250) ' Loop until input is entered.
         End While
         cki = Console.ReadKey(True)
         Console.WriteLine("You pressed the '{0}' key.", cki.Key)
      Loop While cki.Key <> ConsoleKey.X
 
This seems to do exactly the same as what my code above is doing. The loop isn't continuous, I need to press a key to initiate the next iteration. I want the program to loop continuously and stop when I press a key.
 
Code:
' This example demonstrates the Console.KeyAvailable property.

Imports System
Imports System.Threading
Imports Microsoft.VisualBasic

Module Module1

    Sub Main()

        Dim cki As New ConsoleKeyInfo()

        ' Loop here until enter is pressed
        Do
            ' Loop here whilst no key is being pressed
            While Console.KeyAvailable = False
                Console.WriteLine(Format(Date.Now(), "hh:mm:ss") + ": loopy loop")
                Thread.Sleep(100)
            End While

            ' When a key is pressed read it into cki
            cki = Console.ReadKey(True)
            ' And tell the user what they pressed
            Console.WriteLine("You pressed the '{0}' key.", cki.Key)
        Loop While cki.Key <> ConsoleKey.Enter  ' if enter is pressed the out loop will be broken

        Console.WriteLine(vbCrLf + vbCrLf + "Done")
    End Sub

End Module

How about this? I've commented it as well.

Now to go wash my mouth out for using VB (I recently discovered C#) :o.
 
Back
Top Bottom