使用C#调用传统32位API实现串口操作,整个结构特别的简单。接收数据只需要定义数据接收事件即可。
上传源代码我不会,需要源代码的请与我(dyj057@gmail.com)联系。你也可以教我怎么上传源代码。
using System;
using System.Runtime.InteropServices;
namespace Ibms.Tool.IO
{
public class SPRecvDataArgs:EventArgs
{
private byte[] recvData;
public SPRecvDataArgs(byte[] recvData)
{
if( recvData == null)
{
throw(new ArgumentNullException());
}
this.recvData = recvData;
}
public byte[] RecvData
{
get
{
return recvData;
}
}
}
public class IbmsSerialPort:IDisposable
{
#region 平台调用声明代码
[DllImport("IbmsSerialPort.dll")]
public static extern IntPtr Ibms_OpenPort(int nPort, int nRate);
[DllImport("IbmsSerialPort.dll")]
public static extern void Ibms_Close( IntPtr port);
[DllImport("IbmsSerialPort.dll")]
public static extern bool Ibms_SendData( IntPtr port, byte[] data,int nDataSize);
[DllImport("IbmsSerialPort.dll")]
public static extern void Ibms_SetFuncHandle( IntPtr port, HandleFunc handDataFunc);
#endregion
#region 定义字段
public delegate void HandleFunc(IntPtr pData, int nDataSize);
public delegate void RecvData(object sender,SPRecvDataArgs e);
public event RecvData OnRecvData;
private HandleFunc _handleDataFunc;
private int port;
private StanderdRate rate;
private bool openStatus=false;
private IntPtr portHandle;
#region 定义标准的串口波特率
public enum StanderdRate
{
R50=50,
R75=75,
R110=110,
R150=150,
R300=300,
R600=600,
R1200=1200,
R2400=2400,
R4800=4800,
R9600=9600,
R19200=19200,
R38400=38400,
R57600=57600,
R76800=76800,
R115200=115200
};
#endregion
#endregion
#region 定义方法
public IbmsSerialPort()
{
portHandle = (IntPtr)0;
_handleDataFunc = new HandleFunc(OnDllRecvData);
}
public void Open(int nPort, StanderdRate nRate)
{
if(nPort > 255 || nPort < 0)
{
throw(new ArgumentOutOfRangeException());
}
port = nPort;
rate = nRate;
portHandle = Ibms_OpenPort( port, (int)rate );
if( (IntPtr)0 == portHandle )
{
throw( new ApplicationException("打开串口失败"));
}
Ibms_SetFuncHandle( portHandle, _handleDataFunc );
openStatus = true;
}
public void Close()
{
if( openStatus )
{
Ibms_Close( portHandle);
}
openStatus = false;
}
public void SendData( byte[] data )
{
if( !openStatus )
{
throw( new ApplicationException("串口没有打开,发送数据失败") );
}
if( !Ibms_SendData( portHandle, data, data.Length ) )
{
throw( new ApplicationException("串口发送数据失败") );
}
}
unsafe protected void OnDllRecvData(IntPtr pUnhandleData, int nDataSize)
{
int dataSize= nDataSize ;
byte * pData =(byte *) pUnhandleData;
byte[] data = new byte[dataSize];
for(int i=0; i<dataSize; i++)
{
data[i]= pData[i];
}
OnRecvData( this, new SPRecvDataArgs(data) );
}
#endregion
#region 定义属性
public int Port
{
get
{
return port;
}
}
public StanderdRate Rate
{
get
{
return rate;
}
}
public bool OpenStatus
{
get
{
return openStatus;
}
}
#endregion
#region 非托管资源的及时释放
~IbmsSerialPort()
{
Dispose( false );
}
protected virtual void Dispose( bool disposing )
{
if( disposing )
{
}
Close();
}
#region IDisposable 成员
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize(this);
}
#endregion
#endregion
}
}