这是我的表单键事件
窗口2
public void Form2_KeyUp(object sender, KeyEventArgs e)
{
LogKeyEvent(e.KeyCode);
}
public void LogKeyEvent(Keys e)
{
//listBox1.Items.Add(e.KeyCode);
using (StreamWriter sw = new StreamWriter(@"d:\Prova.txt", true))
{
sw.Write(e);
sw.Close();
}
}
的Class2
现在我想从另一个类使用c#提出它,类代码就是这个
private void OnEventArrived(object sender, System.Management.EventArrivedEventArgs e2)
{
if (activewindows == "Command Propmpt") {
LogKeyEvent(Key.L); //from another class
}
}
f是表单对象但是如何将参数传递给此事件并引发它或实际上我想要引发KeyEventArgs是他们的任何其他方式实际上我正在制作一个键记录器
错误1名称' Key'在当前上下文中不存在
答案 0 :(得分:0)
为什么不将此日志记录与另一个public
方法分开,并将其用作从两个类中的事件调用的实例方法?
public void LogKeyEvent(Keys e)
{
listBox1.Items.Add(e);
using(StreamWriter sw = new StreamWriter(@"d:\Prova.txt", true))
{
sw.Write(e);
sw.Close();
}
}
现在可以从具有实例引用的类调用此方法。
public void Form2_KeyUp(object sender, KeyEventArgs e)
{
LogKeyEvent(e.KeyCode);
}
和其他班级
if (ti == "Command Propmpt")
{
f.LogKeyEvent(keyCode);
}
答案 1 :(得分:0)
提升"表格关键活动" 气味;您实际想要的是执行在"表格加密事件"上执行的例程。所以我建议提取方法:
之前:
// Smells:
// 1. Ugly arguments:
// sender (what is it? Can I ,say, pass 123 as a sender)
// e (why on Earth should I generate event args when all I want is to append a file?!)
// 2. Wrong name: Form2_KeyUp (very bad name to writing file routine)
public void Form2_KeyUp(object sender, KeyEventArgs e) {
listBox1.Items.Add(e.KeyCode);
// wrap IDisposable into using
StreamWriter sw = new StreamWriter(@"d:\Prova.txt", true);
sw.Write(e.KeyCode);
sw.Close();
}
后:
//TODO: please, think over the right name
public void AppendKeyCode(Keys keyCode) {
listBox1.Items.Add(keyCode);
File.AppendAllText(@"d:\Prova.txt", keyCode.ToString());
}
// Please, notice "private": do not expose such methods
private void Form2_KeyUp(object sender, KeyEventArgs e) {
AppendKeyCode(e.KeyCode);
}
从其他表单致电AppendKeyCode
:
if (ti == "Command Propmpt") {
// If you have many Form2 opened, let's take the last one
Form2 form = Application.OpenForms
.OfType<Form2>()
.LastOrDefault();
if (form != null)
form.AppendKeyCode(Keys.F1); //TODO: put right key code here
}