Is there a way to automatically capture all FormClosed events in C # in an application?

I would like to centralize a code handler for all FormClosed events, is there a way to automatically notify all forms that close?

+2


source to share


3 answers


subscribe to an event handler after the form is created. those. use + =

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Craft
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var f = new Form2();            
            f.FormClosing += ClosingMonitorer;
            f.Show();

            var g = new Form3();
            g.FormClosing += ClosingMonitorer;
            g.Show();
        }

        void ClosingMonitorer(object sender, FormClosingEventArgs e)
        {            
            MessageBox.Show((sender as Form).Text + " is closing");
        }



    }
}

      



[EDIT: or you can use extension methods to simplify the event subscription process)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Craft
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var f = new Form2();
            f.Show(ClosingMonitorer);            


            var g = new Form3();
            g.Show(ClosingMonitorer);

        }

        void ClosingMonitorer(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show((sender as Form).Text + " is closing");
        }



    }

    public static class Helper
    {
        public static void Show(this Form f, FormClosingEventHandler feh)
        {
            f.FormClosing += feh;
            f.Show();
        }
    }
}

      

+2


source


Subclass Form

and in the constructor connect some function to the event itself FormClosed

? Something like the following:

public class MyForm : Form
{
    public MyForm(FormClosedEventHandler handler) : base()
    {
        this.FormClosed += handler;
    }
}

      

And then just use MyForm

instead Form

as the base word for all your forms.



EDIT: If you have some kind of static function somewhere that you want to use as a handler for all events FormClosed

, you can of course use:

    public MyForm() : base()
    {
        this.FormClosed += Program.MyFormClosedHandler;
    }

      

But this is a little bad (hard to test, see dependency injection) and you can use constructor chaining to achieve the same result.

+3


source


It's not easy for me to understand, but if you want to learn some new techniques, you can do it with aspect-oriented programming.

-2


source







All Articles