1

I'm trying to create a basic program for now which displays live inputs as they are typed. An example output would be something like this:

Current inputs: CTRL ALT S V SPACE

(Note that these would be the currently held keys. If the user released the CTRL key, that input would disappear). I created some sample code here. It's quite crude, but it's my best attempt at this. It's inside a larger program (which I use as a sandbox), but the only context that should be needed is that using System; is at the top of the program

    public static void KeypressTest()
    {
        char[] keys = new char[10];
        int x;
        while (1==1)
        {
            for (x = 0; x < 10; x++) //All the loops attempt to fill the array if possible. I figured this was the easiest way to store multiple characters at once
            {
                keys[x] = Convert.ToChar(ConsoleKey.MediaStop); //I don't know how to set it to blank, so I picked a character that isn't likely to be used
            }
            for (x = 0; x < 10; x++)
            {
                if (keys[x] != Convert.ToChar(ConsoleKey.MediaStop)) { x += 1; } //This skips the key if it is not the default (MediaStop). This is temporary and will be altered once I can figure out how to register a key has been lifted
                else { keys[x] = Console.ReadKey().KeyChar; }
            }
            Console.Write("\rCurrent inputs: \n");
            for (x = 0; x < 10; x++)
            { Console.Write(Convert.ToString(keys[x])); }
            Console.WriteLine();
        }
    }

The code itself has the problem of waiting for all 10 inputs, then displaying the keys typed, and ignoring the release of keys. It seems to act more like a keylogger than the target of showing currently held keys. Example output would look like this, if the user types "hello everyone!!!!!":

Current inputs:

hello ever

Current inputs:

yone!!!!!

The target would show each key for the instant it is held, and would not show it once released (but I have no idea how to go about this).

The problem is, I'm quite new to C# and haven't found a way to update the inputs as they are typed (I am aware of Console.ReadKey() but I don't know how to make it run in the background. I know what threading is but have no knowledge on how to do it, so any tips would be appreciated. Thanks!

Community
  • 1
  • 1
  • Welcome to Stack Overflow! Please provide some code showing the steps you have already tried. – Adrian Mole Sep 20 '19 at 11:25
  • Does it have to be a Console program? can it be a windows form program ? – AntiqTech Sep 20 '19 at 11:46
  • 1
    @AntiqTech Yes, it does have to be console. I'm completely inexperienced with Windows Forms (I'm currently a fresh A-Level student, so we haven't learned a thing about them yet). – ImSoBored927 Sep 20 '19 at 13:08
  • 1
    @Adrian Thanks! I'll update the request with any code I can dig up (I'm not on a computer with access to an IDE at the moment) – ImSoBored927 Sep 20 '19 at 13:09

1 Answers1

0

I've changed my answer, this is closer to what you wanted. I've found a keydown event implementation in this thread (NativeKeyboard internal class): C# arrow key input for a console app

Solution lies with multiple threading timers checking values or conditions in conjunction. Main program thread is in a loop until exit condition is met(pressing ESC key). There is a prompter timer which prints a cache of values denoting a list of pressed keys, to the same line after line is cleared with white spaces. For every ConsoleKey enum, a timer is created and timer-key duo is mapped. Whenever a key is pressed, that key's mapped timer will be able to determine that specific key is pressed and updates the list with key's value/string. Whenever a key is released, list is also updated with an empty string value for that key.

I had to add LocalModifiers enum as key codes for ALT,CTRL,SHIFT and CAPS LOCK.

I had to use lock() to make sure all those timers could work without creating a concurrency problem.

When I executed the code, It had the output very close to what you described. Sometime a few of the pressed keys are not shown in case of 7-8 keys are pressed.

Here is my code:

 class Program
{
    public static Dictionary<int, String> inputMap = new Dictionary<int, string>();
    public static Dictionary<Timer, ConsoleKey> TimerKeyMap = new Dictionary<Timer, ConsoleKey>();
    public static Dictionary<Timer, LocalModifiers> TimerModifierMap = new Dictionary<Timer, LocalModifiers>();
    public static bool continueLoop = true;
    public static object locker = new object();
    static void Main(string[] args)
    {
        Program program = new Program();
        program.run();
    }
    public enum LocalModifiers :int
    {
        SHIFT = 0x10,
        CTL = 0x11,
        ALT = 0x12,
        CAPS_LOCK = 0x14
    }
    public void run()
    {
        Timer keyPressedPrompter = new Timer();
        keyPressedPrompter.Interval = 60;
        keyPressedPrompter.Elapsed += new ElapsedEventHandler(KeyPressedPrompterEvent);
        keyPressedPrompter.Enabled = true;
        foreach (ConsoleKey key in Enum.GetValues(typeof(ConsoleKey)))
        {
            Timer timer = new Timer();
            TimerKeyMap[timer] = key;
            timer.Interval = 60;
            timer.Elapsed += new ElapsedEventHandler(KeyPressedCheckerEvent);
            timer.Enabled = true;
        }
        foreach (LocalModifiers key in Enum.GetValues(typeof(LocalModifiers)))
        {
            Timer timer = new Timer();
            TimerModifierMap[timer] = key;
            timer.Interval = 60;
            timer.Elapsed += new ElapsedEventHandler(ModifierPressedCheckerEvent);
            timer.Enabled = true;
        }
        Console.WriteLine("Current inputs:");
        while (continueLoop) { }
    }
    public static void ModifierPressedCheckerEvent(object source, EventArgs e)
    {
        lock (locker)
        {
            if (NativeKeyboard.IsKeyDown((int)TimerModifierMap[(Timer)source]))
            {
                //Console.WriteLine(KeyTimerMapReverse[(Timer)source].ToString()+ " pressed");
                inputMap[(int)TimerModifierMap[(Timer)source]] = TimerModifierMap[(Timer)source].ToString() + " ";
            }
            else
            {
                // Console.WriteLine(KeyTimerMapReverse[(Timer)source].ToString() + " released");
                inputMap[(int)TimerModifierMap[(Timer)source]] = "";

            }
        }
    }
    public static void KeyPressedCheckerEvent(object source, EventArgs e)
    {
        lock (locker)
        {
            if (NativeKeyboard.IsKeyDown((int)TimerKeyMap[(Timer)source]))
            {
                if (TimerKeyMap[(Timer)source] == ConsoleKey.Escape)
                    continueLoop = false;
                //Console.WriteLine(KeyTimerMapReverse[(Timer)source].ToString()+ " pressed");
                inputMap[(int)TimerKeyMap[(Timer)source]] = TimerKeyMap[(Timer)source].ToString() + " ";
            }
            else
            {
                // Console.WriteLine(KeyTimerMapReverse[(Timer)source].ToString() + " released");
                inputMap[(int)TimerKeyMap[(Timer)source]] = "";

            }
        }
    }
    public static void KeyPressedPrompterEvent(object source, EventArgs e)
    {
        Console.Write("                                             ");//clear the line - -  can be extended
        Console.Write("\r");

        lock (locker)
        {
            foreach (KeyValuePair<int, String> entry in inputMap)
            {
                // do something with entry.Value or entry.Key
                Console.Write(entry.Value);
            }
        }

    }
}

/// <summary>
/// Provides keyboard access.
/// </summary>
internal static class NativeKeyboard
{
    /// <summary>
    /// A positional bit flag indicating the part of a key state denoting
    /// key pressed.
    /// </summary>
    private const int KeyPressed = 0x8000;

    /// <summary>
    /// Returns a value indicating if a given key is pressed.
    /// </summary>
    /// <param name="key">The key to check.</param>
    /// <returns>
    /// <c>true</c> if the key is pressed, otherwise <c>false</c>.
    /// </returns>
    public static bool IsKeyDown(int key)
    {
        return (GetKeyState((int)key) & KeyPressed) != 0;
    }

    /// <summary>
    /// Gets the key state of a key.
    /// </summary>
    /// <param name="key">Virtuak-key code for key.</param>
    /// <returns>The state of the key.</returns>
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern short GetKeyState(int key);
}
AntiqTech
  • 717
  • 1
  • 6
  • 10
  • 1
    This worked perfectly! I'm going to make sure I spend a night or two learning how it works so I can do it on my own for the future, but still. Thanks so much! – ImSoBored927 Sep 23 '19 at 07:44
  • You can ask If you have any questions regarding solutions. I'll try to answer. – AntiqTech Sep 23 '19 at 14:30