Threads, forms, and controls

  • Thread starter Thread starter Jon Slaughter
  • Start date Start date
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
 
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
 
Back
Top