前一阵,从国外网站看到一个用C#来操作串口的类。下载下来试了一下,觉得不错。共享一下。
/*
* Author: Marcus Lorentzon, 2001
* d98malor@dtek.chalmers.se
*
* Freeware: Please do not remove this header
*
* File: SerialStream.cs
*
* Description: Implements a Stream for asynchronous
* transfers and COMM. Stream version.
*
* Version: 2.4
*
*/
#region Using
using System;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using System.ComponentModel;
#endregion Using
namespace LoMaN.IO {
public class SerialStream : Stream {
#region Attributes
private IOCompletionCallback m_IOCompletionCallback;
private IntPtr m_hFile = IntPtr.Zero;
private string m_sPort;
private bool m_bRead;
private bool m_bWrite;
#endregion Attributes
#region Properties
public string Port {
get {
return m_sPort;
}
set {
if (m_sPort != value) {
Close();
Open(value);
}
}
}
public override bool CanRead {
get {
return m_bRead;
}
}
public override bool CanWrite {
get {
return m_bWrite;
}
}
public override bool CanSeek {
get {
return false;
}
}
public bool Closed {
get {
return m_hFile.ToInt32() 0;
}
}
public bool Dsr {
get {
uint status;
if (!GetCommModemStatus(m_hFile, out status)) {
throw new Win32Exception();
}
return (status & MS_DSR_ON) > 0;
}
}
public bool Ring {
get {
uint status;
if (!GetCommModemStatus(m_hFile, out status)) {
throw new Win32Exception();
}
return (status & MS_RING_ON) > 0;
}
}
public bool Rlsd {
get {
uint status;
if (!GetCommModemStatus(m_hFile, out status)) {
throw new Win32Exception();
}
return (status & MS_RLSD_ON) > 0;
}
}
#endregion Properties
#region Constructors
public SerialStream() : this(FileAccess.ReadWrite) {
}
public SerialStream(FileAccess access) {
m_bRead = ((int)access & (int)FileAccess.Read) != 0;
m_bWrite = ((int)access & (int)FileAccess.Write) != 0;
unsafe {
m_IOCompletionCallback = new IOCompletionCallback(AsyncFSCallback);
}
}
public SerialStream(string port) : this(FileAccess.ReadWrite) {
Open(port);
}
public SerialStream(string port, FileAccess access) : this(access) {
Open(port);
}
#endregion Constructors
#region Methods
public void Open(string port) {
if (m_hFile != IntPtr.Zero) {
throw new IOException("Stream already opened.");
}
m_sPort = port;
m_hFile = CreateFile(port, (uint)((m_bRead?GENERIC_READ:0)|(m_bWrite?GENERIC_WRITE:0)), 0, 0,