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);
Related
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();
}
In my game you can control unit, each unit have spell, and we would like to give to the user the possibility to change the keybinding of his different spell.
The goal is for exemple having the possibility to have a combinaison of input for a spell (exemple : "ctrl + H" send the spell)
I find on the unity Store a plugin named "Rewired" that seem to do that, but it's cost 40€and handle too many feature that I don't want.
So I try to create myself my own script to solve my issue, but I don't know how to create the combination of 2 keycode pressed.
This is my script bellow, do you have any idea on how can I create this ?
KeyCode key;
KeyCode curModifiersKey;(alt, ctrl)
KeyCode nonModifierKey;
KeyCode firstModifierKeyInfo;
KeyCode finalKey;
public void DetectedSeveralInput(KeyCode key)
{
if (key != KeyCode.AltGr)
{
if (key == KeyCode.LeftAlt || key == KeyCode.RightAlt || key == KeyCode.LeftControl || key == KeyCode.RightControl)
{
if (modifierPressedCount == 0)
{
firstModifierKeyInfo = key;
modifierPressedCount += 1;
}
curModifiersKey = key;
}
nonModifierKey = key;
//finalKey = curModifiersKey + nonModifierKey
LogVariables();
}
else
{
Debug.Log("AltGR pressed");
return;
}
}
What I do to detect multiple key press is like this
void Update()
{
bool shiftPressed = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
bool keyPressed = Input.GetKeyUp( /* other key code here */ );
if(shiftPressed && keyPressed)
{
//Do logic here
}
}
I check shift key being held with Input.GetKey, but makes sure that the logic only happens once by making the other check an Input.GetKeyUp so it will only be true on key release.
Thanks Tricko for the answer.
But the issue is that i can't do this sytem when you got like 10 units, who have 4 spells.
My reference on it is Starcraft 2 where you have a full panel for your own keybinding when you can add mouse button or ctrl/shift/alt also.
That why i want to so something that save the 2 input into one (if it's possible) and relate it to the speel n°X for my unit Y
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
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
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!")
}
}