Your class should not change the Form.
However, you can create a delegate or an event in your class, and let your class raise that event when some action has to be taken.
Your form can attach an eventhandler to this event, and execute the apropriate action.
For instance:
class MyClass
{
public event EventHandler DoSomething;
public void DoWork()
{
// do some stuff
// raise the DoSomething event.
OnDoSomething(EventArgs.Empty);
}
protected virtual void OnDoSomething(EventArgs args )
{
// This code will make sure that you have no IllegalThreadContext
// exceptions, and will avoid race conditions.
// note that this won't work in wpf. You could also take a look
// at the SynchronizationContext class.
EventHandler handler = DoSomething;
if( handler != null )
{
ISynchronizeInvoke target = handler.Target as ISynchronizeInvoke;
if( target != null && target.InvokeRequired )
{
target.Invoke (handler, new object[]{this, args});
}
else
{
handler(this, args);
}
}
}
}
And, in your Form, you do this:
MyClass c = new MyClass();
c.DoSomething += new EventHandler(MyClass_DoSomething);
c.DoWork();
private void MyClass_DoSomething(object sender, EventArgs e )
{
// Manipulate your form
textBox1.Text = " ... ";
}
When you want to pass some data from your class to your form, then you can make use of the generic EventHandler delegate, and create your own EventArgs class, which contains the information that your form needs.
public class MyEventArgs : EventArgs
{
public string SomeData
{ get;
private set;
}
public MyEventArgs( string s )
{
this.SomeData = s;
}
}
Then offcourse, you'll have to use the generic eventhandler in your class, and pass the appropriate data into the constructor of your own eventargs class.
In the eventhandler, you can then use this data.