前一陣,從國外網站看到一個用C#來操作串口的類。下載下來試了一下,覺得不錯。共享一下。
/*
* Author: Marcus Lorentzon, 2001
*
[email protected] *
* 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;
}
}