-3

I have to create this console based application and I have this problem: I have created something like a KeyListener using multithreading (can't do simple loop, because there is a second thread running simultaneously). And the loop in a thread needs to check if pressed key is an integer.

What is that I don't understand?

The way I get this: there is an infinite loop within the thread that tries to capture the input and if the input == 1 it writes text in the console. What am I missing?

static void KeyRead()
{            
    do
    {
        int i = (int) Console.ReadKey().KeyChar;
        if (i == 1) {
           Console.Out.Write("Key 1 pressed");
        }
    } while (true);
}

static void Main(string[] args)
{
    Thread keyListner = new Thread(new ThreadStart(KeyRead));
    keyListner.Start();                   
}
user3079834
  • 2,009
  • 2
  • 31
  • 63
mafiozorek
  • 49
  • 6
  • _"What is that i don't understand?"_ -- What is your question? What _specifically_ is the code doing that you don't want it to do and you can't figure out how to fix? – Peter Duniho Apr 15 '17 at 06:02
  • It does basically nothing. That's the problem. It's just like there was no "if" statement. What should be done to make it execute the code after if statement? I start the application, I press "1" and nothing happens although it should write "Key 1 pressed". – mafiozorek Apr 15 '17 at 06:10
  • 1
    Your program wouldn't work even without the thread. http://stackoverflow.com/questions/28955029/how-do-i-convert-a-console-readkey-to-an-int-c-sharp – Kevin Gosse Apr 15 '17 at 06:20

1 Answers1

2

KeyChar returns value of type char and casting char to int returns unicode value representing that character. But character '1' have unicode value 49, not 1. So you have to modify condition to compare i to be eqaual to 49 instead of 1.

static void KeyRead()
{
    do
    {
        int i = (int)Console.ReadKey().KeyChar;
        if (i == 49)
        {
            Console.Out.Write("Key 1 pressed");
        }
    } while (true);
}

But it is even beter to avoid this integer conversion altogether and compare character directly:

static void KeyRead()
{
    do
    {
        char c = Console.ReadKey().KeyChar;
        if (c == '1')
        {
            Console.Out.Write("Key 1 pressed");
        }
    } while (true);
}
Ňuf
  • 6,027
  • 2
  • 23
  • 26