private void btnConnect_Click(object sender, RoutedEventArgs e) { if (!port.IsOpen) { try { port.PortName = (string)portList.SelectedItem; port.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK); return; } btnConnect.Content = "Disconnect"; state.IsChecked = true; timer.Change(0, 1000); } else { btnConnect.Content = "Connect"; timer.Change(Timeout.Infinite, 1000); while (task.Status == TaskStatus.Running) { DisapcherHelper.DoEvents(); } port.Close(); state.IsChecked = false; } }
private void Window_Closed(object sender, EventArgs e) { timer.Change(Timeout.Infinite, 1000); while (task.Status == TaskStatus.Running) { DisapcherHelper.DoEvents(); } port.Close(); timer.Dispose(); }
private void btnRefresh_Click(object sender, RoutedEventArgs e) { if (port.IsOpen) { btnConnect.Content = "Connect"; timer.Change(Timeout.Infinite, 1000); while (task.Status == TaskStatus.Running) { DisapcherHelper.DoEvents(); } port.Close(); } string[] pts = SerialPort.GetPortNames(); portList.Items.Clear(); foreach (var i in pts) { portList.Items.Add(i); } }