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.
We can take string input in C using scanf(“%s”, str).
\0 is zero character. In C it is mostly used to indicate the termination of a character string.
\n (New line) – We use it to shift the cursor control to the new line. \t (Horizontal tab) – We use it to shift the cursor to a couple of spaces to the right in the same line.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With