Threads, forms, and controls

J

Jon Slaughter

Is this scenario possible?

One has a form, a thread and a control. The thread adds a control to the
form. The form adds handlers to every control added but because the control
is in a different thread the handler might cause an exception.

If this is possible how to I prevent it from happening?

in my form I do

this.ControlRemoved += new
System.Windows.Forms.ControlEventHandler(this.Control_Removed);

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



private void Control_Added(object sender,
System.Windows.Forms.ControlEventArgs e)

{

e.Control.LostFocus += new EventHandler(Control_LostFocus);

e.Control.MouseEnter += new EventHandler(Control_MouseEnter);

e.Control.MouseLeave += new EventHandler(Control_MouseLeave);

}

private void Control_Removed(object sender,
System.Windows.Forms.ControlEventArgs e)

{

e.Control.LostFocus -= new EventHandler(Control_LostFocus);

e.Control.MouseEnter -= new EventHandler(Control_MouseEnter);

e.Control.MouseLeave -= new EventHandler(Control_MouseLeave);

}





and I'm worried that it could cause issues ;/



Thanks,

Jon
 
L

Laurent Bugnion

Hi,

Jon said:
Is this scenario possible?

One has a form, a thread and a control. The thread adds a control to the
form. The form adds handlers to every control added but because the control
is in a different thread the handler might cause an exception.

You cannot modify the UI elements from another thread than the UI
thread. To pass events to the UI thread from another thread, you must
use the System.Windows.Forms.Control.Invoke method.
http://msdn2.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx

To check if you need Invoke or not, use the Control.InvokeRequired property.

HTH
Laurent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top