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?
views:
24answers:
3
+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
2010-05-31 22:10:32
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.
2010-06-01 03:43:10
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
2010-05-31 22:55:33
+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.