C# com口监听
时间: 2023-07-12 11:09:57 浏览: 75
要在C#中监听COM口,可以使用`System.IO.Ports`命名空间中的`SerialPort`类。以下是一个简单的示例代码:
```csharp
using System.IO.Ports;
public class SerialPortWrapper
{
private SerialPort _serialPort;
public SerialPortWrapper(string portName, int baudRate)
{
_serialPort = new SerialPort(portName, baudRate);
_serialPort.DataReceived += SerialPortDataReceived;
_serialPort.Open();
}
public void Write(byte[] data)
{
_serialPort.Write(data, 0, data.Length);
}
public void Close()
{
_serialPort.Close();
_serialPort.Dispose();
}
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadExisting();
// 处理接收到的数据
}
}
```
在上述代码中,我们封装了一个名为`SerialPortWrapper`的类来处理COM口的读写操作。在构造函数中,我们传入了COM口名称和波特率,并创建了`SerialPort`对象。我们还通过`DataReceived`事件订阅了数据接收事件,并在事件处理程序中处理接收到的数据。
`Write`方法用于向COM口写入数据,`Close`方法用于关闭COM口连接并释放资源。
这只是一个简单的示例,实际应用中可能需要更复杂的逻辑来处理COM口的读写操作。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)