class EventLogging
{
static void Log(string title, object sender, EventArgs e)
{
Console.WriteLine("Event: {0}", title);
Console.WriteLine(" Sender: {0}", sender);
Console.WriteLine(" Arguments: {0}", e.GetType());
foreach (PropertyDescriptor prop in //enter键没输出
TypeDescriptor.GetProperties(e))
{
string name = prop.DisplayName;
object value = prop.GetValue(e);
Console.WriteLine(" {0}={1}", name, value);
}
}
static void Main() //在事件处理程序中进行记录 用Lambda表达式记录事件
{
Button button = new Button();
button.Text = "Click me";
button.Click += (src, e) => Log("Click", src, e); //enter键或者鼠标点击
button.KeyPress += (src, e) => Log("KeyPress", src, e);
//键盘上的某些键触发
button.MouseClick += (src, e) => Log("MouseClick", src, e);
//鼠标点击 触发
Form form = new Form();
form.AutoSize = true;
form.Controls.Add(button);
Application.Run(form);
}
}
我们想记录事件的本质,又想记录与发送者和实参有关的信息,用Lambda表达式
用Lambda表达式将事件名称和事件的参数传给记录事件细节的Log方法。
除了由事件来源的ToString覆盖的版本返回的内容之外,我们没有记录事件来源的
其他任何细节,由于与控件关联的信息实在是太多了。
对属性描述符(Property Descriptor)使用反射技术,从而展示传递的EventArgs
实例的细节。
输出 视情况而定 鼠标点击,按键盘的一个键都可输出
Event: Click //鼠标点击触发
Sender: System.Windows.Forms.Button, Text: Click me
Arguments: System.Windows.Forms.MouseEventArgs
Button=Left
Clicks=1
X=18
Y=10
Delta=0
Location={X=18,Y=10}
Event: MouseClick
Sender: System.Windows.Forms.Button, Text: Click me
Arguments: System.Windows.Forms.MouseEventArgs
Button=Left
Clicks=1
X=18
Y=10
Delta=0
Location={X=18,Y=10}
Event: Click //enter键触发
Sender: System.Windows.Forms.Button, Text: Click me
Arguments: System.EventArgs
Event: KeyPress //按1触发
Sender: System.Windows.Forms.Button, Text: Click me
Arguments: System.Windows.Forms.KeyPressEventArgs
KeyChar=1
Handled=False