2016-11-28 39 views
0

所以我有一个包含以下代码的处理程序:如何将我的Form1 frm变量分配给现有的/加载的表单对象?

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; 
    } 

第4行我创建一个Form1中的对象,我想将其设置为现有的,已经运行,form1的对象。如何以语法方式访问该对象?

回答

1

Form1行为有点像Singleton

添加静态Form1成员Form1

public static Form1 instance; 

将其设置为Form1的构造:

instance = this; 

,然后访问它在你的代码是这样的:

Form1.instance 
+0

这非常完美,非常感谢 –

相关问题