I am trying to post text from a class into an active form and I am having a little trouble figuring out how to do it. I have seen a bunch about using Invoking to post things across threads/forms but I can’t get my class to see any public functions in the activeform.
Example
// File: Form1.cs
namespace Form1
{
public partial class Form1 : Form
{
public void SetText(string text)
{
this.Invoke((MethodInvoker) delegate { \\ Always requires invoke
TextBox1.Text += text + "\n";
});
}
}
Then my second class that is being run in a second thread (because it is a long process)
// File: Class.cs
using Form1;
namespace Form1
{
public void DoSomething() // Called in Form1
{
// Does stuff
string TextToGoBack; // Has text when DoSomething runs
// Here is where I get stuck
Form form = Form1.ActiveForm;
form.SetText(TextToGoBack); // SetText is not showing up here no matter what I do
}
}
EDIT:
I would not be opposed to using custom events to accomplish the same thing, but I am having a tough time figuring those out as well.
Form.ActiveFormreturns aFormobject, not the instance of yourForm1class, so does not have aSetTextmethod.You could cast it to a
Form1, but that would be brittle. I would pass the instance ofForm1to yourDoSomethingmethod.