tags:

views:

24

answers:

3

I have a use case where any text box created in the application should be handled and some events should be listened to. I checked the ControlCollection, it does not seem to have a "created" or "modified" events. Also MessageFilter could not receive any create, or destroy events. Is this an optimal way to receive messages or windows hook will be the only alternative?

+1  A: 

Try using ControlAdded and ControlRemoved events. Example:

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

        this.ControlAdded += new System.Windows.Forms.ControlEventHandler(this.Form1_ControlAdded);

        TextBox nameTextBox = new TextBox();
        nameTextBox.Text = "John";
        this.Controls.Add(nameTextBox);
    }

    private void Form1_ControlAdded(object sender, ControlEventArgs e)
    {
        TextBox addedTextBox = e.Control as TextBox;
        if(addedTextBox != null)
        {
            MessageBox.Show(addedTextBox.Text);
        }
    }
}
abespalov
This worked very well when control is directly added to the container. Did not handle if a container inside the form is updated, so plugged on to the container in turn helped.
A: 

The Control class has the Disposed event. You could wire that up to detect that the control got disposed. It is more reliable than the ControlAdded/Removed events since adding or removing a control doesn't automatically means it is being disposed.

Hans Passant
+1  A: 

Found one more solution using hooks. Code from codeproject helped. Started a CBT hook just before creating the first form. This helped capture all "Create" and "Destroy" events.