static public bool button_COMOpen_Click(SerialPort sp) { MyTimer MyTmr = null; for (int i = 0; i < list_timer_scan_com.Count; i++) { if (list_timer_scan_com[i].serialport == sp) { MyTmr = list_timer_scan_com[i]; break; } } Dbg.Assert(MyTmr != null, "###Why can not find SP!?"); bool res = false; if ((MyTmr.button_COMOpen.ForeColor == Color.Red) && (sp.IsOpen == false)) //打开串口 { if (Open(sp) == true) { MyTmr.Enabled = true; res = true; } } else if ((MyTmr.button_COMOpen.ForeColor == Color.Green) && (sp.IsOpen == true)) //关闭串口 { MyTmr.Enabled = false; Close(sp); //重建一次com number 列表,因为可能COM口有变化,同样的select下次打不开了 int temp_select_index = MyTmr.comboBox_COMNumber.SelectedIndex; Ruild_ComNumberList(MyTmr.comboBox_COMNumber); if (MyTmr.comboBox_COMNumber.Items.Count > temp_select_index) { MyTmr.comboBox_COMNumber.SelectedIndex = temp_select_index; } } //关闭窗口的时候,如果串口已经掉了,则会进来这里,触发comboBox_COMNumber_SelectedIndexChanged,不走关闭串口的路径,列表会重新建立 else if ((MyTmr.button_COMOpen.ForeColor == Color.Green) && (sp.IsOpen == false)) { MyTmr.comboBox_COMNumber.SelectedIndex = -1; } //拔掉COM之后,is open会变成false 的 else { Dbg.Assert(false, "###TODO: What is this statue?!"); } return(res); }
static public void Timer_ScanCOM_Add(SerialPort _serialport, ComboBox _comboBox_COMNumber, Button _button_COMOpen, ty_delegate_SetComStatus _delegate_SetComStatus) { MyTimer timer_ScanCOM = new MyTimer(); timer_ScanCOM.serialport = _serialport; timer_ScanCOM.comboBox_COMNumber = _comboBox_COMNumber; timer_ScanCOM.button_COMOpen = _button_COMOpen; timer_ScanCOM.delegate_SetComStatus = _delegate_SetComStatus; timer_ScanCOM.Elapsed += new System.Timers.ElapsedEventHandler(Timer_ScanCOM_Tick); timer_ScanCOM.AutoReset = true; timer_ScanCOM.Enabled = false; timer_ScanCOM.Interval = 1000; list_timer_scan_com.Add(timer_ScanCOM); }
static void Timer_ScanCOM_Tick(object sender, EventArgs e) { MyTimer timer_ScanCOM = sender as MyTimer; if ((timer_ScanCOM.button_COMOpen.ForeColor == Color.Green) && (timer_ScanCOM.serialport.IsOpen == false)) { timer_ScanCOM.Enabled = false; MessageBox.Show("COM: " + timer_ScanCOM.serialport.PortName + " is lost!", "Warning!"); Close(timer_ScanCOM.serialport); //this.Invoke((EventHandler)(delegate //{ // Ruild_ComNumberList(timer_ScanCOM.comboBox_COMNumber); // timer_ScanCOM.delegate_SetComStatus(false); //})); Ruild_ComNumberList(timer_ScanCOM.comboBox_COMNumber); timer_ScanCOM.delegate_SetComStatus(false); } }