detect key press - c#

I have a code where I do something when a Key is pressed
if (Console.ReadKey(true).Key == ConsoleKey.G)
{
Logger.Trace("Opening the GUI...");
}
How to detect if key is pressed by using character as A-B? I store shortcut letter in file and want to know if pressed but need to detect it by string and not ConsoleKey.

You can use char.IsLetter() to check if its an alphabet
ConsoleKeyInfo keyinfo;
Console.ReadKey();
while (!(Console.KeyAvailable ))
{
keyinfo = Console.ReadKey();
if (char.IsLetter(Console.ReadKey().KeyChar))
{
}
}

Save the Console.ReadKey result into a string variable and append further keystrokes and check with
if(inputString.Contains(key)){
doSomething()
}
Have a look at the following answers:
https://stackoverflow.com/a/16037492/4992212
Detect when two keys are pressed at the same time

Related

How to read keys that user presses without specifying the exact key?

Basically what I need is an idea how to shorten my code.
So what I have now is an IF series to get the keys that user presses:
if (Input.GetKeyDown(KeyCode.I))
{
AddToBuffer("I");
}
else if (Input.GetKeyDown(KeyCode.N))
{
AddToBuffer("N");
}
else if (Input.GetKeyDown(KeyCode.F))
{
AddToBuffer("F");
}
It works perfectly well, but what I want is to shorten it so it would be possible to save to buffer any key (better, as a string)
So that I would no more have to specify what key was pressed.
(Maybe something like TryParse etc.)
InputString contains a string all keys pressed down on the current frame. It is recommended to break the string down into characters as shown in the input string example in Unity documentation, as inputString can contain backspace '\b' and enter '\n' characters.
An example of listening for cheatcodes might look like this:
string cheatCode = "money";
int cheatIndex = 0;
void Update()
{
if(Input.anyKeyDown)
{
foreach (char c in Input.inputString)
{
if(c == cheatCode[cheatIndex])
{
//the next character was entered correctly
Debug.Log("The next character {0} was entered correctly", c);
//On the next key down, check the next character
cheatIndex++;
} else
{
//The character was not correctly entered, reset the cheat index back to the start of the code
Debug.Log("Cheat code invalid. {0} was not the next character", c);
cheatIndex = 0;
}
}
if(cheatIndex == cheatCode.Length)
{
Debug.Log("Cheat code was successfully entered")
}
}
}
I have not written this in Unity and tested it, so your mileage may vary.
You can use "any key": https://docs.unity3d.com/ScriptReference/Input-anyKey.html
if (Input.anyKey)
{
Debug.Log("A key or mouse click has been detected");
// get the pressed key:
String keycode = Event.current.keyCode.ToString();
}

Detect key combination being pressed in C# console app

I have a pretty simple console app thats quietly waits for a users to press a key, then performs an action based on the what key was pressed. I had some issues with it, but some helpful users over on this post pointed out where I was going wrong.
The code I currently have to handle a single key press is as follows
ConsoleKey key;
do
{
while (!Console.KeyAvailable)
{
// Do something, but don't read key here
}
// Key is available - read it
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.NumPad1)
{
Console.WriteLine(ConsoleKey.NumPad1.ToString());
}
else if (key == ConsoleKey.NumPad2)
{
Console.WriteLine(ConsoleKey.NumPad2.ToString());
}
} while (key != ConsoleKey.Escape);
I'm wondering how I can detect when a combination of 2 or more keys is pressed. I'm not talking about the standard Ctrl + c, but rather something like Ctrl + NumPad1. If a user presses Ctrl + NumPad1, perform action X.
I'm really unsure how to go about doing this, as the current while loop will only loop until a single key is pressed, so wont detect the second key (assuming that its litterally impossible to press two keys at the exact same time.
Is anyone able to provide a steer in the right direction to help achieve this?
I guess you need to check the key modifier. Check the pseudo code below:
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine(keyInfo.Key);
Console.WriteLine(keyInfo.Modifier);
...
if((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) Console.WriteLine("CTL+");
If you capture the ConsoleKeyInfo, you will get additional information, including the Modifiers keys. You can query this to see if the Control key was pressed:
ConsoleKey key;
do
{
while (!Console.KeyAvailable)
{
// Do something, but don't read key here
}
// Key is available - read it
var keyInfo = Console.ReadKey(true);
key = keyInfo.Key;
if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
{
Console.Write("Ctrl + ");
}
if (key == ConsoleKey.NumPad1)
{
Console.WriteLine(ConsoleKey.NumPad1.ToString());
}
else if (key == ConsoleKey.NumPad2)
{
Console.WriteLine(ConsoleKey.NumPad2.ToString());
}
} while (key != ConsoleKey.Escape);

React to keypress during text output in Console application

I am writing a text adventure in c# for a school assignment and I've already come across a problem.
I made a function to type out sentences like this:
public static void Zin (string zin)
{
foreach (char c in zin)
{
Console.Write(c);
Thread.Sleep(50);
}
Now this works but I want to implement that when the player hits the enter key, the sentence is typed out on the console instantly.
I'm not sure how to do this. I've tried using a while loop in the foreach loop that checks wether enter is being hit and then print out the sentence but that doesn't work.
Thanks in advance!
You can use the Console.KeyAvailable property to find out whether keys have been pressed that have not been read via any of the Console.Read* methods.
When keys have been pressed, skip the waiting within the loop. After the loop, read all keys that have been pressed during the loop, so that they will not be returned when you use Console.Read* later on.
public static void Zin(string zin)
{
foreach (char c in zin)
{
Console.Write(c);
// Only wait when no key has been pressed
if (!Console.KeyAvailable)
{
Thread.Sleep(50);
}
}
// When keys have been pressed during our string output, read all of them, so they are not used for the following input
while (Console.KeyAvailable)
{
Console.ReadKey(true);
}
}
See also Listen for key press in .NET console app

Detect if a key is down without waiting for key press in C# console application [duplicate]

This question already has answers here:
Listen for key press in .NET console app
(10 answers)
Closed 9 years ago.
How can I check whether a specific key is down, and do nothing if another or no key is pressed?
I want something like this pseudocode in a Visual C# console application:
while (true) {
if (IsKeyDown(Escape)) { //checks if Escape is down
println("Press enter to resume");
waitKey(Enter); //waits until Enter is pressed
}
//do something
}
This loop will keep doing something, until the Escape key is pressed. If the Escape key is pressed, the loop will pause until the Enter key is pressed.
I've tried:
Console.ReadKey() - will just pause the loop until any key is pressed.
Keyboard.IsKeyDown() - has no effect in a console application.
Is this what you are looking for?
using System;
class Example
{
public static void Main()
{
ConsoleKeyInfo cki;
// Prevent example from ending if CTL+C is pressed.
Console.TreatControlCAsInput = true;
Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
Console.WriteLine("Press the Escape (Esc) key to quit: \n");
do
{
cki = Console.ReadKey();
Console.Write(" --- You pressed ");
if((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
if((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
if((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
Console.WriteLine(cki.Key.ToString());
} while (cki.Key != ConsoleKey.Escape);
}
}
http://msdn.microsoft.com/en-us/library/471w8d85%28v=vs.110%29.aspx

Detecting key presses in console [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to handle key press event in console application
a simple question.
I am writing a simple text based adventure game for fun and I am stuck on the first part already! How can I make my console check for key presses I.E: press enter to continue!
You can use
Console.ReadKey();
To read 1 key. You could then do something like this:
string key = Console.ReadKey().Key.ToString();
if(key.ToUpper() == "W")
Console.WriteLine("User typed 'W'!");
else
Console.WriteLine("User did not type 'W'");
Or:
if(key == "")
Console.WriteLine("User pressed enter!");
else
Console.WriteLine("User did not press enter.");
And if you do not care if the user types anything but presses enter after, you could just do:
// Some code here
Console.ReadLine();
// Code here will be run after they press enter
The Console class contains all the methods needed to read and write to the 'console'
For example
Console.Write("Press Enter to continue!")
do
{
ConsoleKeyInfo c = Console.ReadKey();
} while (c.Key != ConsoleKey.Enter);
Console.Write("Press Enter to continue!")
Console.ReadLine();
The program will not continue until the user hits Enter.
You can also check for other specific keys using Console.ReadKey:
void WaitForKey(ConsoleKey key)
{
while (Console.ReadKey(true).Key != key)
{ }
}
Usage:
Console.Write("Press 'Y' to continue.");
WaitForKey(ConsoleKey.Y);
An event, that would do it.
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
Console.Write("Press Enter to continue!")
}
}

Categories

Resources