J.Doe J.Doe - 11 days ago 6
C# Question

How to assign my Form1 frm variable to the existing/loaded form object?

So I have a handler that contains the following code:

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
Form1 frm = //want to set 'frm' to the existing, instantiated form1 already running.
string indata = sp.ReadExisting(); //stores the char that fired the event into 'indata'
if (indata == "\r") //check to see if char received indicates end of measurement, yes tells main form to add measurement, no tells to add char to string
{
frm.pendingMeasurement = true;
MessageBox.Show(myString);
}
else
myString += indata;
}


on line 4 I'm creating a form1 object and I want to set it to the existing, already running, form1 object. How do I access that object syntax-wise?

Answer

Make Form1 behave somewhat like a Singleton:

Add a static Form1 member to Form1:

public static Form1 instance;

Set it in Form1's constructor:

instance = this;

And then access it in your code like this:

Form1.instance