tags:

views:

24

answers:

1

I have an VB.Net Console Application running and I do not want it to close when the user hit the ENTER button, rather I want it to close when they type EXIT and then press ENTER. What should I do?

A: 

Read from the console using Console.ReadLine() (which requires a carriage return to complete).

if (Console.ReadLine() == "EXIT")
{
    Environment.Exit(0); // or, simply return from the Main method
}

Another way to phrase it:

while (Console.ReadLine() != "EXIT")
{
    Console.WriteLine("Didn't say the magic word!");
}

Remember that once you return from your Main method, your console application closes. It's hard to advise you exactly what to do without seeing the logical structure of your application, but remember: if you want to prevent your application from exiting, don't let your Main method return.

Michael Petrotta
@michael:: Dear Friend Its still not working to my purpose.The moment i hit the ENTER button it is getting closed. Even if I am Not typing the wir EXIT before it.
Rajdeep
@Rajdeep: what happens after that block of code? Once you return from your `Main` method, your console application closes. You'll need to block that. I'll edit my answer with an example.
Michael Petrotta
@Michael :: That will be so nice of you.Waiting for your Edited Reply
Rajdeep
@Michael:: I am pasting my code
Rajdeep
Rajdeep
@Rajdeep: add your code to your question, and use the `101010` button to format it. But it looks like some variant of my second example will work for you. Note my last paragraph. What do you want to happen if they type something other than "EXIT"?
Michael Petrotta
@Michael/Egrunin:: Michael, I got what you are trying to say. According to you until and unless i get my specific word i will keep on executing the main() so that it does not return anything.I did that.I wrote: if Console.ReadLine.Trim.ToUpper <> "EXIT" Then Console.WriteLine("") End If
Rajdeep
Above code is also not working.All i want is unless and untill user write anything other than "EXIT", the application will not close
Rajdeep
@Rajdeep: you need to use `while`, not `if`. What you're doing now is equivalent to: *if they type "exit", then write an empty line. Then, whether or not they typed "exit", quit.*
Michael Petrotta
@Michael..In VB.Net '<>' means not equal so i am writting If Console.ReadLine.Trim.ToUpper <> "EXIT" Then Console.WriteLine("") End If
Rajdeep
Look into the difference between [if](http://msdn.microsoft.com/en-us/library/752y8abs.aspx) and [while](http://msdn.microsoft.com/en-us/library/zh1f56zs.aspx). Again: you want to use `while`, not `if`.
Michael Petrotta
@Michael..I got your logic..it was my fault..Thankx a lot Michael.
Rajdeep
@michael:: I appreciate your ans and logic.Thanks for your knowledge.Have a nice day
Rajdeep
@Rajdeep: glad I could help.
Michael Petrotta