Sunday, August 9, 2009

Quick user input with Console.ReadKey()

One of the many useful applications of the Console.ReadKey() method of the .net framework is to get a quick input from the user.
By using this method the user is not required to hit the return key to submit the input.

The following is a simple method which simplifies the process of asking something to the user and getting the answer in the form of a boolean value.
The parameters of the method allow to specify what is the question to ask to the user, what is the default value to return, and what is the non-default key, i.e., the only key that return the opposite of the default value.
The last two parameters allow to specify if the answer is case sensitive and if the user input has to be shown on the terminal.

// Base - The toolbox of the non-project-specific things.
// Copyright (C) 2009 Andrea Esuli
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Andrea Esuli (andrea@esuli.it)
using System;
namespace Esuli.Base
{
	public class ExtendedConsole
	{
		public static bool Ask(string question,bool defaultAnswer,char nondefaultAnswerChar,bool caseSensitive,bool hideChar) {
			Console.Write(question);
			char answer;
			if(caseSensitive)
				answer = Console.ReadKey(hideChar).KeyChar;
			else {
				nondefaultAnswerChar = Char.ToLower(nondefaultAnswerChar);
				answer = Char.ToLower(Console.ReadKey(hideChar).KeyChar);
			}
			Console.WriteLine();
			if(answer==nondefaultAnswerChar)
				return !defaultAnswer;
			else
				return defaultAnswer;
		}
	
		public static void Main(string[] args)
		{
			while(!Ask("Do you want to exit The Loop? (y/N) ", false,'y',false,true))
				Console.WriteLine("Caught in The Loop.");
			Console.WriteLine("Free! Oh no, wait...");
	
			while(!Ask("Do you want to exit The Loop? (y/N) ", false,'y',false,false))
				Console.WriteLine("OMG, The Loop is back! (showing the chars you type)");
			Console.WriteLine("Free, at last.");
		}
	}
}

Add comment

Fill out the form below to add your own comments


Quote

- Sei pronto Jack?
- Io sono nato pronto.

(Grosso guaio a Chinatown)

Latest Tweet

Loading the latest tweet...

Advertising