This commit is contained in:
GukSang.Jin
2026-01-04 14:53:08 +08:00
parent 5494a8a79e
commit 0b3ced2528

View File

@@ -59,10 +59,32 @@ namespace WindowsFormsApp6
_readTimer.Interval = 100; // 100ms检查一次信号量
_readTimer.Tick += ReadTimer_Tick;
// 尝试打开默认串口
if (!TryOpenSerialPort("COM2"))
{
// 如果默认串口失败,弹出端口选择对话框
ShowPortSelectionDialog();
}
}
/// <summary>
/// 尝试打开指定的串口
/// </summary>
private bool TryOpenSerialPort(string portName)
{
try
{
// 如果已有串口打开,先关闭
if (_serialPort != null && _serialPort.IsOpen)
{
_serialPort.Close();
_serialPort.Dispose();
}
// 配置串口参数
_serialPort = new SerialPort
{
PortName = "COM2",
PortName = portName,
BaudRate = 19200,
DataBits = 8,
Parity = Parity.None,
@@ -73,11 +95,7 @@ namespace WindowsFormsApp6
DtrEnable = false
};
try
{
// 打开串口
if (!_serialPort.IsOpen)
{
_serialPort.Open();
// 创建Modbus RTU主站
@@ -89,12 +107,111 @@ namespace WindowsFormsApp6
// 启动定时读取
_readTimer.Start();
ShowInfoMsg("数据采集器初始化成功");
}
ShowInfoMsg($"串口 {portName} 初始化成功");
return true;
}
catch (Exception ex)
{
ShowErrorMsg($"串口/Modbus初始化失败:{ex.Message}");
System.Diagnostics.Debug.WriteLine($"打开串口 {portName} 失败:{ex.Message}");
return false;
}
}
/// <summary>
/// 显示端口选择对话框
/// </summary>
private void ShowPortSelectionDialog()
{
// 获取当前计算机所有可用串口
string[] ports = SerialPort.GetPortNames();
if (ports == null || ports.Length == 0)
{
ShowErrorMsg("未检测到可用的串口,请检查串口连接。");
return;
}
// 创建端口选择对话框
Form portDialog = new Form
{
Text = "选择串口",
Width = 350,
Height = 200,
StartPosition = FormStartPosition.CenterParent,
FormBorderStyle = FormBorderStyle.FixedDialog,
MaximizeBox = false,
MinimizeBox = false
};
Label label = new Label
{
Text = "串口初始化失败,请选择可用的串口:",
Location = new Point(20, 20),
AutoSize = true
};
ComboBox comboBox = new ComboBox
{
Location = new Point(20, 50),
Width = 290,
DropDownStyle = ComboBoxStyle.DropDownList
};
comboBox.Items.AddRange(ports);
if (comboBox.Items.Count > 0)
{
comboBox.SelectedIndex = 0;
}
Button btnOK = new Button
{
Text = "确定",
DialogResult = DialogResult.OK,
Location = new Point(140, 100),
Width = 80
};
Button btnCancel = new Button
{
Text = "取消",
DialogResult = DialogResult.Cancel,
Location = new Point(230, 100),
Width = 80
};
portDialog.Controls.AddRange(new Control[] { label, comboBox, btnOK, btnCancel });
portDialog.AcceptButton = btnOK;
portDialog.CancelButton = btnCancel;
// 显示对话框
if (portDialog.ShowDialog(this) == DialogResult.OK)
{
string selectedPort = comboBox.SelectedItem?.ToString();
if (!string.IsNullOrEmpty(selectedPort))
{
if (TryOpenSerialPort(selectedPort))
{
// 成功打开
return;
}
else
{
// 选择的端口也失败,询问是否重新选择
var result = MessageBox.Show(
$"打开串口 {selectedPort} 失败,是否重新选择?",
"错误",
MessageBoxButtons.YesNo,
MessageBoxIcon.Error);
if (result == DialogResult.Yes)
{
ShowPortSelectionDialog(); // 递归调用,重新选择
}
}
}
}
else
{
ShowErrorMsg("未选择串口,数据采集功能将不可用。");
}
}