press any key to exit

elloco999

Well-known member
Joined
Dec 21, 2004
Messages
49
Programming Experience
5-10
Hi,

I have a small console app that asks the user to press enter t exit. This is done, to let the user read the output before closing the app.

VB.NET:
[size=2]Console.Write("Press The 'Enter' key to close the application.")[/size]
[size=2]Console.Read()[/size]

I would like to change this, so that the user can press any key, instead of just enter. How can I do this?

Greetz,
El Loco
 
Yes, I do ;)

Use following code:
VB.NET:
Sub Main()
   Console.WriteLine("Press Any Key To Continue")
   Return
End Sub

Cya CowZ
 
Nice try Cowz, but fraid not. That just goes through and closes, he want's the user to press a key first. Which other that Enter is as far as I can tell not possible.

TPM
 
@TCM: You're right :( I have another way to do it.. but it produces an error at the moment you hit a key (but you can catch it with try) and it is coded really badly ;)
VB.NET:
Dim b() As Byte
Try
   Console.OpenStandardInput.Read(b, 0, 1)
Catch ex As Exception
End Try

@JuggaloBrotha: That don't work at all, there is (by standard) no Application object in Consoleapplication..
 
Actually, JuggaloBrotha's code works just fine, but you still have to press enter, because of the readline command. I use this code now, but I want to do this without having to press enter. I tried using the Console.Read command (instead of ReadLine), but that didn't help either...

Anyway, thanks all for your input!

Greetz,
El Loco
 
It's doable with my code.. just try it ;)
i mean following:
VB.NET:
Dim b() As Byte
Try
   Console.OpenStandardInput.Read(b, 0, 1)
Catch ex As Exception
End Try
 
It doesn't give you an error if you give a length for b (ie b(1)), BUT you still need to hit enter. With out b(1) it just goes to the error and closes..

TPM
 
why does any key matter? why not simply have the user press the enter key? i'll look up key trapping sometime here
 
@tpm:
I've just tried it.. it works fine..

It gives an error as soon as you press any key.. Then the program ends (as he wished)..

@JuggaloBrotha: It's not the why, but the how ;) (maybe just for fun... ;))
Cya CowZ
 
Last edited:
Er...

It gives an error to you (that's "normal") but you catch this error with try...

If you write b(1) and not b() it won't work.

cya cowz
 
Exactly as you have it, doesn't work for me.

VB.NET:
Dim b() As Byte
Try
   Console.OpenStandardInput.Read(b, 0, 1)
Catch ex As Exception
End Try
 
Tried this and indeed it works great! Thanks.

And as to why I wanted to "press any key" instead of enter: It is more user friendly! What program askes its users to press enter to exit?
Even on my 486 in dos the programs asked to press anykey. I must say I find it a bit strange there is no methode included in the .NET libraries to do this... It has been such a standard way to end a console (or dos) application.

Greets,
El Loco
 
Back
Top