Input from the Keyboard in Command Line Application

Input from the keyboard in command line application

I managed to figure it out without dropping down in to C:

My solution is as follows:

func input() -> String {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
return NSString(data: inputData, encoding:NSUTF8StringEncoding)!
}

More recent versions of Xcode need an explicit typecast (works in Xcode 6.4):

func input() -> String {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
return NSString(data: inputData, encoding:NSUTF8StringEncoding)! as String
}

C# .NET Console Application getting keyboard input

The trick is that you first need to check if there is a KeyAvailable in the cache, and then use ReadKey() to read it. After that, your code should work as you expect. The line of code that does this would look something like:

// Check if there's a key available. If not, just continue to wait.
if (Console.KeyAvailable) { var key = Console.ReadKey(); }

Here's a sample to demonstrate:

public static void Main(string[] args)
{
Console.SetCursorPosition(Console.WindowWidth / 2, Console.WindowHeight / 2);
Console.CursorVisible = false;
Console.Write('*');

var random = new Random();

while (true)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);

switch (key.Key)
{
case ConsoleKey.UpArrow:
if (Console.CursorTop > 0)
{
Console.SetCursorPosition(Console.CursorLeft - 1,
Console.CursorTop - 1);
Console.Write('*');
}
break;
case ConsoleKey.DownArrow:
if (Console.CursorTop < Console.BufferHeight)
{
Console.SetCursorPosition(Console.CursorLeft - 1,
Console.CursorTop + 1);
Console.Write('*');
}
break;
case ConsoleKey.LeftArrow:
if (Console.CursorLeft > 1)
{
Console.SetCursorPosition(Console.CursorLeft - 2,
Console.CursorTop);
Console.Write('*');
}
break;
case ConsoleKey.RightArrow:
if (Console.CursorLeft < Console.WindowWidth - 1)
{
Console.Write('*');
}
break;
}
}

// This method should be called on every iteration,
// and the iterations should not wait for a key to be pressed
// Instead of Frame.Update(), change the foreground color every three seconds
if (DateTime.Now.Second % 3 == 0)
Console.ForegroundColor = (ConsoleColor) random.Next(0, 16);
}
}

Sending keyboard input to a program from command-line

xdotool does have a way of sending keystrokes if limited to a focused window:

WID=`xdotool search "Mozilla Firefox" | head -1`
xdotool windowactivate $WID
xdotool key ctrl+l


Related Topics



Leave a reply



Submit