[英]Monitoring a Windows Forms Application [closed]
我想监视Winforms应用程序内的用户行为。
是否有一种通用方法可以挂接到事件系统,而不必以每种形式或每个按钮编写事件处理程序?
我想监视应用程序中的以下事件:
我不想订阅所有形式的所有事件,该应用程序对此非常重要。 我只想挂接并监视所有事件。
您不需要以每种形式和每种控件编写事件句柄。 您可以将逻辑放在基本Form
类中。
您可以简单地为您的项目创建一个基本表单,然后在其中放置日志逻辑。 在基本表单中,您可以使用代码预订所需的各种事件。
要应用解决方案:
BaseForm
派生所有形式。 只需使用find and replace all命令即可完成。
同样要创建下面的类,不要添加Form
,只需添加一个类并使用下面的类即可:
基本形式
public class BaseForm : Form
{
public BaseForm()
{
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) return;
this.Load += BaseForm_Load;
this.FormClosed += BaseForm_FormClosed;
}
private IEnumerable<Control> GetAllControls(Control control)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAllControls(ctrl)).Concat(controls);
}
void BaseForm_FormClosed(object sender, FormClosedEventArgs e)
{
Log(string.Format("{0} Closed", this.Name));
}
void BaseForm_Load(object sender, EventArgs e)
{
Log(string.Format("{0} Opened", this.Name));
GetAllControls(this).OfType<Button>().ToList()
.ForEach(x => x.Click += ButtonClick);
}
void ButtonClick(object sender, EventArgs e)
{
var button = sender as Button;
if (button != null) Log(string.Format("{0} Clicked", button.Name));
}
public void Log(string text)
{
var file = System.IO.Path.Combine(Application.StartupPath, "log.txt");
text = string.Format("{0} - {1}", DateTime.Now, text);
System.IO.File.AppendAllLines(file, new string[] { text });
}
}
注意
Application.ThreadException
事件。 StopWatch
来计算用户使用表单的时间。 您也可以简单地记录开始时间和结束时间,以及将差值记录为用户使用表单的持续时间。 这是您需要在课堂上使用的:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.