123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using System.Collections.Generic;
- using System.IO.Ports;
- using System.Windows;
- namespace BarrageTransporter
- {
- /// <summary>
- /// SettingsWindow.xaml 的交互逻辑
- /// </summary>
- public partial class SettingsWindow : Window
- {
- AppContext appContext = AppContext.getAppContext();
- SerialTool serialTool = SerialTool.getSerialTool();
- public SettingsWindow()
- {
- InitializeComponent();
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- startOpenBarrage.IsChecked = Properties.Settings.Default.startOpenBarrage;
- if (appContext.PortOpen)
- {
- comboBox.Items.Clear();
- comboBox.Items.Add(appContext.SerialPort.PortName);
- comboBox.SelectedIndex = 0;
- comboBox.IsEnabled = false;
- connect.Content = "断开连接";
- scan.IsEnabled = false;
- }
- else
- {
- connect.Content = "连接设备";
- scan_Click(null, null);
- }
- }
- private void scan_Click(object sender, RoutedEventArgs e)
- {
- // 清除当前串口号中的所有串口名称
- comboBox.Items.Clear();
- List<string> portList = serialTool.findPort();
- if (portList.Count == 0)
- {
- MessageBox.Show("没有找到可用设备!", "提示");
- }
- else
- {
- portList.ForEach(
- delegate (string portName) {
- comboBox.Items.Add(portName);
- });
- //使 ListBox 显示第1个添加的索引
- comboBox.SelectedIndex = 0;
- }
- }
- private void connect_Click(object sender, RoutedEventArgs e)
- {
- if (appContext.PortOpen)
- {
- // 关闭串口
- if (serialTool.closePort(appContext.SerialPort))
- {
- comboBox.IsEnabled = true;
- scan.IsEnabled = true;
- scan_Click(null, null);
- connect.Content = "连接设备";
- appContext.SerialPort = null;
- }
- else
- {
- MessageBox.Show("断开连接失败!", "错误提示");
- }
- }
- else
- {
- // 检测串口设置
- string portName = comboBox.Text.Trim();
- if (portName == "")
- {
- MessageBox.Show("设备设置错误!", "错误提示");
- return;
- }
- // 打开串口
- SerialPort serialPort = serialTool.openPort(portName, "9600", "8", "1", "无", appContext.dataReceived);
- if (serialPort == null)
- {
- // 打开串口失败
- MessageBox.Show("连接设备失败!", "错误提示");
- }
- else
- {
- comboBox.IsEnabled = false;
- scan.IsEnabled = false;
- connect.Content = "断开连接";
- appContext.SerialPort = serialPort;
- }
- }
- }
- private void ok_Click(object sender, RoutedEventArgs e)
- {
- Properties.Settings.Default.startOpenBarrage = (bool)startOpenBarrage.IsChecked;
- Properties.Settings.Default.Save();
- Properties.Settings.Default.Reload();
- this.Close();
- }
- }
- }
|