Monitor opening of Forms C#

Asked

Viewed 105 times

2

I need to monitor the opening of Forms within a C#application. For example, every time you open a Form within the application, the application must execute a method or trigger an event with information from the open form. I searched 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 derive from this BaseForm.

This approach would be the most viable?

There are ways but appropriate to monitor the opening of Forms within an application?

1 answer

3


I can’t talk in detail, I don’t know if he’s suited to what he needs and he’ll be able to adapt to what he needs, he’s likely to have more than he needs, and I don’t like his coding style, but that’s my problem :)

From what you described, it seems to me that’s the basic technique. With the inheritance ensures that all forms have the necessary logic to make the notification of what happened. The use of specific events determines what to monitor.

How will you make the notification, to whom, of what, and what should be notified is something you can change to your need, but this is a good basis.

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

The other way that I see it is safer is to use aspect-oriented programming. But I doubt it’s a better option, even because it’s hard for most people.

  • Thanks for the comments, they helped me solve the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.