Monitor opening of Forms C #

2

I need to monitor the opening of Forms inside a C # application. For example, every time you open a Form within the application, the application must either execute a method or trigger an event with open form information. I researched and found this code:

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

According to the author, all forms must be derived from this BaseForm .

Would this approach be the most viable?

Are there more appropriate ways to monitor the opening of forms within an application?

    
asked by anonymous 16.01.2017 / 13:46

1 answer

3

I can not speak in detail, I do not know if it's right for what it needs, and if you can adapt to what you need, you probably have more things than you need, and I do not like the coding style of it, but that's a problem my:)

From what I've described, it seems to me that the basic technique is this. With inheritance ensures that all forms have the logic needed to make the notification of what happened. Using specific events determines what to monitor.

How you will notify, to whom, what, and what is to be notified is something that you can change for your need, but that is a good basis.

Obviously it has the flaw of not working if someone does not derive from that class, but that would be a major development error.

The other way I see it to be safer is to use aspect-oriented programming. But I doubt it's a better option.

    
16.01.2017 / 14:10