型号:1900
波特率(Baud Rate):9600
端口名称(Port Name):COM
实现加载窗口后自动聚焦
完整代码
//MainWindow.xaml
<Window x:Class="ScannerConnect.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ScannerConnect"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox x:Name="Scanning" Text="" FontSize="20" HorizontalAlignment="Left" Height="35" Margin="150,80,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="440" />
</Grid>
</Window>
//MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.IO.Ports;
using System.Windows.Threading;
namespace ScannerConnect
{
public partial class MainWindow : Window
{
private SerialPort myComPort; //扫码枪端口
public MainWindow()
{
InitializeComponent();
InitializeSerialPort();
}
private void InitializeSerialPort()
{
myComPort = new SerialPort();
myComPort.BaudRate = 9600;
myComPort.Parity = Parity.None;
int portNumber = DetectAvailablePort();
if (portNumber != -1)
{
myComPort.PortName = $"COM{portNumber}";
myComPort.DataReceived += ReceiveData;
// 尝试打开串行端口
try
{
myComPort.Open();
}
catch (IOException ex)
{
MessageBox.Show("无法打开串行端口: " + ex.Message);
myComPort.Dispose(); // 释放串行端口资源
}
}
else
{
MessageBox.Show("没有找到可用的串行端口。");
}
}
private bool IsPortAvailable(string portName)
{
try
{
using (SerialPort port = new SerialPort(portName))
{
port.Open();
port.Close();
return true; // 端口未被占用
}
}
catch (IOException)
{
return false; // 端口被占用
}
}
private int DetectAvailablePort()
{
for (int i = 1; i <= 10; i++) // 通常COM端口编号从1开始,这里检测到COM10
{
string portName = $"COM{i}";
if (IsPortAvailable(portName))
{
return i; // 返回可用端口编号
}
}
return -1; // 没有找到可用端口
}
private void ReceiveData(object sender, SerialDataReceivedEventArgs e)//接收数据
{
try
{
int n = myComPort.BytesToRead;
byte[] buf = new byte[n];
myComPort.Read(buf, 0, n);
// 将字节数组转换为字符串
string receivedData = Encoding.ASCII.GetString(buf);
// 使用 Dispatcher.Invoke 确保 UI 更新在 STA 线程中执行
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
Scanning.Text = receivedData; // 直接更新 TextBox 文本
}));
}
catch (IOException ex)
{
MessageBox.Show("读取串行端口数据时发生错误: " + ex.Message);
}
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (myComPort != null)
{
myComPort.Close();
myComPort.Dispose(); // 释放串行端口资源
}
}
//设置加载窗口的时候把焦点聚焦到TextBox上
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Scanning.Focus();
}
}
}
【运行结果】:
Tip:当你编译运行后,没有报错,且一切正常,就是运行窗口没有弹出来,可以结束运行,然后在项目文件夹中找到“bin”>“Debug”,在“Debug”中找到“.exe”可执行文件,双击手动启动。