J.Doe J.Doe - 1 year ago 114
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;
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 Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download