2016-11-28 2 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 «s:

instance = this; 

И затем к нему доступ в вашем коде:

Form1.instance 
+0

Это прекрасно, спасибо большое –

Смежные вопросы