How to write a string using readkey inside a loop? - c#

I am making a program in which I need the user input to be invisible, and I read that var key = System.Console.ReadKey(true); does just that.
To do what I need, however I need a string with multiple characters, so what I've done is
string Choice1=null;
User1Input:
while (true)
{
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
break;
}
Choice1 += key;
}
What is happening is that key simply doesn't read anything, because even if I press enter, the loop does not close.

So your sole intention is to hide the character while user types input in console. In that case you are in right track and your posted code looks good except the last line which says Choice1 += key;. It should be
Choice1 += key.KeyChar;
Your posted code with bit modification
string choice1=null; //casing of variable names
while (true)
{
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
break;
choice1 += key.KeyChar;
}

Related

How to use Console.ReadKey() while avoiding the same key being registered constantly after, C#

I would like to make a program which will let the user decide what program to run, by pressing certain keys. I have now come so far that some of these keys work perfectly. However I have now come to a problem that I have a difficult time to solve. Now when I press a key it activates the same thing that was activated before even though I press a different key. I believe that the issue lies in the WaitForKey()-method, but I am not sure where in there. Can you help me to locate the issue and bring in some solutions to this?
note: hasBeenPressed is a Boolean value which tells if the key has already been pressed or not and if so it should avoid activating some other functionality automatically.
public static void WaitForKey(ConsoleKey key) {
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key == key && hasBeenPressed == false) {
hasBeenPressed = true;
return;
}
else if (keyInfo.Key == key) {
hasBeenPressed = false;
return;
}
}
I use the WaitForKey() in this context:
for (int i = 0; i < mySignalChain.Count - 1; i++) {
if (keyPress.Key == ConsoleKey.I) {
pedalsActivated(mySignalChain)
WaitForKey(ConsoleKey.I);
}
I hope this was clear otherwise I will try to elaborate on this.
Thanks in advance!
Based on the description of what you would like to achieve,
I would like to make a program which will let the user decide what program to run, by pressing certain keys.
I wrote the following Console Application that will execute a different function depending on the key you press (I, J, or K), and will keep asking for keys until the user presses a different key, in which case the program will finish.
var exit = false;
ConsoleKeyInfo keyInfo;
do
{
Console.WriteLine("Please enter a new Key");
keyInfo = Console.ReadKey();
Console.WriteLine();
switch (keyInfo.Key)
{
case ConsoleKey.I:
FunctionFor_I();
break;
case ConsoleKey.J:
FunctionFor_J();
break;
case ConsoleKey.K:
FunctionFor_K();
break;
default:
ExitProgram();
break;
}
}
while (exit == false);
void FunctionFor_I()
{
Console.WriteLine("I has been pressed");
}
void FunctionFor_J()
{
Console.WriteLine("J has been pressed");
}
void FunctionFor_K()
{
Console.WriteLine("K has been pressed");
}
void ExitProgram()
{
exit = true;
}
I tried to replicate your code first and see how it works, but I couldn't understand its purpose so I focused on your textual description of the problem. If this is not what you intended, please post the full version of your code and I'll try to reproduce it.
I have now fixed my issue (somewhat) by doing the following:
ConsoleKeyInfo keyPress = Console.ReadKey(true);
while (keyPress.Key != ConsoleKey.Q) {
switch (keyPress.Key) {
case ConsoleKey.I:
pedalsActivated(mySignalChain);
Console.WriteLine("");
WaitForKey(ConsoleKey.I);
keyPress = Console.ReadKey(true);
break;
.
.
.
}
By using my function WaitForKey() defined above I can now activate my functions while at the same time avoiding a certain key being spammed. But then I also reset the keyPress (by: keyPress = Console.Readkey(true);) so that other functions can be called with other keys - though I have to press every key twice now to do so. This works better than having to press the keys far more than twice - however it would be optimal if I would only need to press each key once. And if anyone has an idea how to do so it would be much appreciated.

Is there a way to get an input in the console without having to press the enter key?

I want to be able to get single characters from the console without having to press the enter key.
For example, when I press the letter "e", I want to immediately use that value without the user having to press the enter key
Try:
var key = System.Console.ReadKey(intercept: true);
The intercept flag prevents the pressed key from being rendered into the terminal.
What yoy need is Console.ReadKey().
For example:
ConsoleKeyInfo key = Console.ReadKey(); // Read pressed key
char c = key.KeyChar; // char...
string s = c.ToString(); // ... or string, depending on what you need.
As already suggested, you can try type Console. in VS and see which members are available.
Hope this is what you are looking for!
Reference: How to handle key press event in console application
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press 'Shift+Q' to exit.");
do {
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift)
&& keyInfo.Key == ConsoleKey.Q)
{
break;
}
// TODO : Write your code here
Console.WriteLine(keyInfo.KeyChar);
} while (true);
}
}
}

Use infinite loop to restart program on any key press and to leave loop on specific key press

I currently have user entering a value for temperature and am giving recommendation based on temperature. I would like to setup a loop to ask the user for input until the user presses either "N" or "n".
For example:
//user input
//temp recommendation
//Continue? Press any key, N or n to exit.
Any key pressed would again ask for user input and N or n would result in program thanking user on screen no longer showing temp recommendation. Professor suggested we use additional method to achieve expected result.
Current incorrect code:
Console.WriteLine("Continue? Press any key to continue, N or n to exit:\n");
{
if (Console.ReadKey().Key == ConsoleKey.N)
else if (Console.ReadKey().Key == ConsoleKey.n)
return;}
}
Console.WriteLine("Thank you");
You can make use of a local variable in a while loop as follows:
static void main(string[] args)
{
bool keepGoing = true;
while (keepGoing)
{
DoYourWork();
Console.WriteLine("Continue? Press any key to continue, N or n to exit:");
var userWantsToContinue = Console.ReadLine();
keepGoing = userWantsToContinue?.ToUpper() != "N";
}
}
You can use break to exit from loop
while(true)
{
//process temperature conversion
Console.Write("Continue? Press any key to continue, N or n to exit:");
if (Console.ReadKey().Key == ConsoleKey.N)
{
break;
}
}
Enter the do..while loop :)
private static void DoWhatever(string data)
{
// process your temp
}
// inside main somewhere
Console.WriteLine("Enter temp:");
do
{
var temp = Console.ReadLine();
DoWhatever(temp);
Console.WriteLine("Continue? Press any key to continue, N or n to exit:\n");
}while(Console.ReadKey().Key != ConsoleKey.N);
Console.WriteLine("Thank you");

How to put some text in C# console instead of user typing it in?

In my C# console application, I prompt user to insert the ip address:
string strIpAddress;
Console.WriteLine("Type the IP Address:");
strIpAddress = Console.ReadLine();
Output looks like this:
I want to put the default IP address text ready on console for user to see and just hit the ENTER. If the default IP is invalid then user should be able to delete the text (with backspace), correct the IP address, then hit the ENTER. User should see something like this:
I don't know how to do this! ;-(
Thanks for any sugestion.
Edited to allow for user editing
Console.Write("Type the IP Address:\n");
SendKeys.SendWait("192.168.1.1"); //192.168.1.1 text will be editable :)
strIpAddress=Console.ReadLine();
This requires adding the System.Windows.Forms to the references and adding the namespace.
A more sophisticated example using Console.SetCursorPosition() to move the cursor to the left (if possible) and Console.ReadKey() to read the keys directly to intercept Backspace presses and enter keys:
using System;
using System.Linq;
namespace StackoverflowTests
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Type the IP Address: ");
//Put the default IP address
var defaultIP = "192.168.0.190";
Console.Write(defaultIP);
string input = defaultIP;
//Loop through all the keys until an enter key
while (true)
{
//read a key
var key = Console.ReadKey(true);
//Was this is a newline?
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
//Was is a backspace?
else if (key.Key == ConsoleKey.Backspace)
{
//Did we delete too much?
if (Console.CursorLeft == 0)
continue; //suppress
//Put the cursor on character back
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
//Delete it with a space
Console.Write(" ");
//Put it back again
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
//Delete the last char of the input
input = string.Join("", input.Take(input.Length - 1));
}
//Regular key? add it to the input
else if(char.IsLetterOrDigit(key.KeyChar))
{
input += key.KeyChar.ToString();
Console.Write(key.KeyChar);
} //else it must be another control code (ESC etc) or something.
}
Console.WriteLine("You entered: " + input);
Console.ReadLine();
}
}
}
Can be made even more sophisticated if you want to add support for LeftArrow and RightArrow presses, or even UpArrow presses for recalling the last typed in stuff.

C# - Use ReadKey for loop

I have been searching the web for about an hour and I just can't find the answer to my question. I'm very new to programming and I hope I'm not wasting your time. I want my program to loop if I would click "Y", exit if I click "N" and do nothing if I click any other button. Cheers!
Console.Write("Do you wan't to search again? (Y/N)?");
if (Console.ReadKey() = "y")
{
Console.Clear();
}
else if (Console.ReadKey() = "n")
{
break;
}
You have an example here of Console.ReadKey method :
http://msdn.microsoft.com/en-us/library/471w8d85.aspx
//Get the key
var cki = Console.ReadKey();
if(cki.Key.ToString() == "y"){
//do Something
}else{
//do something
}
You are missing keystrokes this way. Store the return of Readkey so you can split it out.
Also, comparison in C# is done with == and char constants use single quotes (').
ConsoleKeyInfo keyInfo = Console.ReadKey();
char key = keyInfo.KeyChar;
if (key == 'y')
{
Console.Clear();
}
else if (key == 'n')
{
break;
}
you can use the keychar to check that character is pressed
Use can understand that by following example
Console.WriteLine("... Press escape, a, then control X");
// Call ReadKey method and store result in local variable.
// ... Then test the result for escape.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed escape!");
}
// Call ReadKey again and test for the letter a.
info = Console.ReadKey();
if (info.KeyChar == 'a')
{
Console.WriteLine("You pressed a");
}
// Call ReadKey again and test for control-X.
// ... This implements a shortcut sequence.
info = Console.ReadKey();
if (info.Key == ConsoleKey.X &&
info.Modifiers == ConsoleModifiers.Control)
{
Console.WriteLine("You pressed control X");
}
Presumably by "do nothing" you intend that the user be asked to try pressing a valid key until they do. You can use a do statement (a.k.a. do loop) to repeat some code while some condition is true, for example:
var validKey = false;
var searchAgain = false;
do
{
Console.Write("Do you want to search again? (Y/N): ");
string key = Console.ReadKey().KeyChar.ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine();
if (key == "y")
{
validKey = true;
searchAgain = true;
}
else if (key == "n")
{
validKey = true;
searchAgain = false;
}
else
{
Console.WriteLine("Please press the 'Y' key or the 'N' key.");
}
} while (!validKey);
// Now do something depending on the value of searchAgain.
I used the "not" in !validKey because it reads better that way: do {this code} while (the user hasn't pressed a valid key). You might prefer to use a while loop if you think the code reads better with that construction.
The .ToLower(System.Globalization.CultureInfo.InvariantCulture) bit is so that it doesn't matter if "y" or "Y" is pressed, and it has a very good chance of working with any letter, even the ones that have unexpected upper/lower case variations; see Internationalization for Turkish:
Dotted and Dotless Letter "I" and What's Wrong With Turkey? for explanation of why it's a good idea to be careful about that kind of thing.

Categories