Running two codes at the same time

I want to read the password(Text) input while keeping the “CapsLock = true/false” readout up to date while the user is typing in Console application C#

User is Typing
Show Capslock is on/off

is it need using threading or not??

Thank for watching thank for answer and thank for help me guys.. ty

  • “User is Typing Show Capslock is on/off” – Show where?

    – 




  • If CapsLock is on, your Console.Read/ReadLine will return the capitalized character. What do you mean?

    – 

That’s weird, but possible.

First problem is that Console won’t let you write something until user finish his input. So you won’t be able to handle CapsLock press “on-the-fly” and notify user about its state change. Even from separate threads.
But you can use MessageBox from PresentationCore.dll or System.Windows.Forms.dll and show it independently.

Second problem is that you can’t properly handle CapsLock press as some sort of KeyPress event. So you need manually check and detect its state changes.

I’ve got things work with this example:

 using System;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 // ...

 private static string PromptUserPassword()
 {
     // Flag to stop CapsLock state checks after user input
     var passwordInputted = false;

     // Run CapsLock state checks loop somewhere in background
     Task.Run(async () =>
     {
         // "Remember" current CapsLock state
         var capsLockLastState = Console.CapsLock;

         while (!passwordInputted)
         {
             // When CapsLock state changed - notify about that with MessageBox and "remember" new state
             if (Console.CapsLock != capsLockLastState)
             {
                 capsLockLastState = Console.CapsLock;
                 MessageBox.Show($"CapsLock is turned {(Console.CapsLock ? "ON" : "OFF")}");
             }

             await Task.Delay(10);
         }
     });

     // Ask user password
     Console.WriteLine("Please, input your password:");
     var password = Console.ReadLine();
     // "Break" CapsLock state checks loop
     passwordInputted = true;

     return password;
 }

And from somewhere in code in need to call just var password = PromptUserPassword();

There is a lot of nuances with this code, such as you can just “ignore” shown MessageBox and keep switching CapsLock and then receive tonns of MessageBox’es.

That example provided just for
familiarization
. I highly recommend NOT to use this in real authorization purposes, and probably migrate into WPF or WindowsForms at least for proper implementations.

Leave a Comment