引用kernel32.dll中的API来进行串口通讯
串口通讯可以引出kernel32.dll中的api来操作,相关源码如下:
using system;
using system.runtime.interopservices;
namespace telehome.gsm
{
/// <summary>
/// ************************************************************************************
///
/// function: 连接,断开串口;发送,接收串口数据,使用kernel32.dll中相关串口操作
/// 函数对com口进行操作
///
/// author: telehome.hzyong
///
/// datetime: 2005-11-20
///
/// ************************************************************************************
/// </summary>
public class commport
{
/// <summary>
/// 端口名称(com1,com2...com4...)
/// </summary>
public string portnum;
/// <summary>
/// 波特率9600
/// </summary>
public int baudrate;
/// <summary>
/// 数据位4-8
/// </summary>
public byte bytesize;
/// <summary>
/// 奇偶校验0-4=no,odd,even,mark,space
/// </summary>
public byte parity;
/// <summary>
/// 停止位
/// </summary>
public byte stopbits; // 0,1,2 = 1, 1.5, 2
/// <summary>
/// 超时长
/// </summary>
public int readtimeout;
/// <summary>
/// com口句柄
/// </summary>
private int hcomm = -1;
/// <summary>
/// 串口是否已经打开
/// </summary>
public bool opened = false;
/// <summary>
/// winapi常量,写标志
/// </summary>
private const uint generic_read = 0x80000000;
/// <summary>
/// winapi常量,读标志
/// </summary>
private const uint generic_write = 0x40000000;
/// <summary>
/// winapi常量,打开已存在
/// </summary>
private const int open_existing = 3;
/// <summary>
/// winapi常量,无效句柄
/// </summary>
private const int invalid_handle_value = -1;
/// <summary>
/// 设备控制块结构体类型
/// </summary>
[structlayout(layoutkind.sequential)]
public struct dcb
{
/// <summary>
/// dcb长度
/// </summary>
public int dcblength;
/// <summary>
/// 指定当前波特率
/// </summary>
public int baudrate;
/// <summary>
/// 指定是否允许二进制模式
/// </summary>
public int fbinary;
/// <summary>
/// 指定是否允许奇偶校验
/// </summary>
public int fparity;
/// <summary>
/// 指定cts是否用于检测发送控制,当为true是cts为off,发送将被挂起。
/// </summary>
public int foutxctsflow;
/// <summary>
/// 指定cts是否用于检测发送控制
/// </summary>
public int foutxdsrflow;
/// <summary>
/// dtr_control_disable值将dtr置为off, dtr_control_enable值将dtr置为on, dtr_control_handshake允许dtr"握手"
/// </summary>
public int fdtrcontrol;
/// <summary>
/// 当该值为true时dsr为off时接收的字节被忽略
/// </summary>
public int fdsrsensitivity;
/// <summary>
/// 指定当接收缓冲区已满,并且驱动程序已经发送出xoffchar字符时发送是否停止。
/// true时,在接收缓冲区接收到缓冲区已满的字节xofflim且驱动程序已经发送出
/// xoffchar字符中止接收字节之后,发送继续进行。 false时,在接收缓冲区接
/// 收到代表缓冲区已空的字节xonchar且驱动程序已经发送出恢复发送的xonchar之
/// 后,发送继续进行。xoff continues tx
/// </summary>
public int ftxcontinueonxoff;
/// <summary>
/// true时,接收到xoffchar之后便停止发送接收到xonchar之后将重新开始 xon/xoff
/// out flow control
/// </summary>
public int foutx;
/// <summary>
/// true时,接收缓冲区接收到代表缓冲区满的xofflim之后,xoffchar发送出去接收
/// 缓冲区接收到代表缓冲区空的xonlim之后,xonchar发送出去 xon/xoff in flow control
/// </summary>
public int finx;
/// <summary>
/// 该值为true且fparity为true时,用errorchar 成员指定的字符代替奇偶校验错误
/// 的接收字符 enable error replacement
/// </summary>
public int ferrorchar;
/// <summary>
/// etrue时,接收时去掉空(0值)字节 enable null stripping
/// </summary>
public int fnull;
/// <summary>
/// rts flow control rts_control_disable时,rts置为off rts_control_enable时, rts置为on
/// rts_control_handshake时,当接收缓冲区小于半满时rts为on当接收缓冲区超过四分之
/// 三满时rts为off rts_control_toggle时,当接收缓冲区仍有剩余字节时rts为on ,否则
/// 缺省为off
/// </summary>
public int frtscontrol;
/// <summary>
/// true时,有错误发生时中止读和写操作 abort on error
/// </summary>
public int fabortonerror;
/// <summary>
/// 未使用
/// </summary>
public int fdummy2;
/// <summary>
/// 标志位
/// </summary>
public uint flags;
/// <summary>
/// 未使用,必须为0
/// </summary>
public ushort wreserved;
/// <summary>
/// 指定在xon字符发送这前接收缓冲区中可允许的最小字节数
/// </summary>
public ushort xonlim;
/// <summary>
/// 指定在xoff字符发送这前接收缓冲区中可允许的最小字节数
/// </summary>
public ushort xofflim;
/// <summary>
/// 指定端口当前使用的数据位
/// </summary>
public byte bytesize;
/// <summary>
/// 指定端口当前使用的奇偶校验方法,可能为:evenparity,markparity,noparity,oddparity 0-4=no,odd,even,mark,space
/// </summary>
public byte parity;
/// <summary>
/// 指定端口当前使用的停止位数,可能为:onestopbit,one5stopbits,twostopbits 0,1,2 = 1, 1.5, 2
/// </summary>
public byte stopbits;
/// <summary>
/// 指定用于发送和接收字符xon的值 tx and rx xon character
/// </summary>
public char xonchar;
/// <summary>
/// 指定用于发送和接收字符xoff值 tx and rx xoff character
/// </summary>
public char xoffchar;
/// <summary>
/// 本字符用来代替接收到的奇偶校验发生错误时的值
/// </summary>
public char errorchar;
/// <summary>
/// 当没有使用二进制模式时,本字符可用来指示数据的结束
/// </summary>
public char eofchar;
/// <summary>
/// 当接收到此字符时,会产生一个事件
/// </summary>
public char evtchar;
/// <summary>
/// 未使用
/// </summary>
public ushort wreserved1;
}
/// <summary>
/// 串口超时时间结构体类型
/// </summary>
[structlayout(layoutkind.sequential)]
private struct commtimeouts
{
public int readintervaltimeout;
public int readtotaltimeoutmultiplier;
public int readtotaltimeoutconstant;
public int writetotaltimeoutmultiplier;
public int writetotaltimeoutconstant;
}
/// <summary>
/// 湓出缓冲区结构体类型
/// </summary>
[structlayout(layoutkind.sequential)]
private struct overlapped
{
public int internal;
public int internalhigh;
public int offset;
public int offsethigh;
public int hevent;
}
/// <summary>
/// 打开串口
/// </summary>
/// <param name="lpfilename">要打开的串口名称</param>
/// <param name="dwdesiredaccess">指定串口的访问方式,一般设置为可读可写方式</param>
/// <param name="dwsharemode">指定串口的共享模式,串口不能共享,所以设置为0</param>
/// <param name="lpsecurityattributes">设置串口的安全属性,win9x下不支持,应设为null</param>
/// <param name="dwcreationdisposition">对于串口通信,创建方式只能为open_existing</param>
/// <param name="dwflagsandattributes">指定串口属性与标志,设置为file_flag_overlapped(重叠i/o操作),指定串口以异步方式通信</param>
/// <param name="htemplatefile">对于串口通信必须设置为null</param>
[dllimport("kernel32.dll")]
private static extern int createfile(string lpfilename, uint dwdesiredaccess, int dwsharemode,
int lpsecurityattributes, int dwcreationdisposition, int dwflagsandattributes, int htemplatefile);
/// <summary>
/// 得到串口状态
/// </summary>
/// <param name="hfile">通信设备句柄</param>
/// <param name="lpdcb">设备控制块dcb</param>
[dllimport("kernel32.dll")]
private static extern bool getcommstate(int hfile, ref dcb lpdcb);
/// <summary>
/// 建立串口设备控制块
/// </summary>
/// <param name="lpdef">设备控制字符串</param>
/// <param name="lpdcb">设备控制块</param>
[dllimport("kernel32.dll")]
private static extern bool buildcommdcb(string lpdef, ref dcb lpdcb);
/// <summary>
/// 设置串口状态
/// </summary>
/// <param name="hfile">通信设备句柄</param>
/// <param name="lpdcb">设备控制块</param>
[dllimport("kernel32.dll")]
private static extern bool setcommstate(int hfile, ref dcb lpdcb);
/// <summary>
/// 读取串口超时时间
/// </summary>
/// <param name="hfile">通信设备句柄</param>
/// <param name="lpcommtimeouts">超时时间</param>
[dllimport("kernel32.dll")]
private static extern bool getcommtimeouts(int hfile, ref commtimeouts lpcommtimeouts);
/// <summary>
/// 设置串口超时时间
/// </summary>
/// <param name="hfile">通信设备句柄</param>
/// <param name="lpcommtimeouts">超时时间</param>
[dllimport("kernel32.dll")]
private static extern bool setcommtimeouts(int hfile, ref commtimeouts lpcommtimeouts);
/// <summary>
/// 读取串口数据
/// </summary>
/// <param name="hfile">通信设备句柄</param>
/// <param name="lpbuffer">数据缓冲区</param>
/// <param name="nnumberofbytestoread">多少字节等待读取</param>
/// <param name="lpnumberofbytesread">读取多少字节</param>
/// <param name="lpoverlapped">溢出缓冲区</param>
[dllimport("kernel32.dll")]
private static extern bool readfile(int hfile, byte[] lpbuffer, int nnumberofbytestoread,
ref int lpnumberofbytesread, ref overlapped lpoverlapped);
/// <summary>
/// 写串口数据
/// </summary>
/// <param name="hfile">通信设备句柄</param>
/// <param name="lpbuffer">数据缓冲区</param>
/// <param name="nnumberofbytestowrite">多少字节等待写入</param>
/// <param name="lpnumberofbyteswritten">已经写入多少字节</param>
/// <param name="lpoverlapped">溢出缓冲区</param>
[dllimport("kernel32.dll")]
private static extern bool writefile(int hfile, byte[] lpbuffer, int nnumberofbytestowrite,
ref int lpnumberofbyteswritten, ref overlapped lpoverlapped);
[dllimport("kernel32.dll", setlasterror=true)]
private static extern bool flushfilebuffers(int hfile);
[dllimport("kernel32.dll", setlasterror=true)]
private static extern bool purgecomm(int hfile, uint dwflags);
/// <summary>
/// 关闭串口
/// </summary>
/// <param name="hobject">通信设备句柄</param>
[dllimport("kernel32.dll")]
private static extern bool closehandle(int hobject);
/// <summary>
/// 得到串口最后一次返回的错误
/// </summary>
[dllimport("kernel32.dll")]
private static extern uint getlasterror();
/// <summary>
/// 建立与串口的连接
/// </summary>
public void open()
{
dcb dcbcommport = new dcb();
commtimeouts ctocommport = new commtimeouts();
// 打开串口
hcomm = createfile(portnum ,generic_read | generic_write, 0, 0, open_existing, 0, 0);
if(hcomm == invalid_handle_value)
{
return;
}
// 设置通信超时时间
getcommtimeouts(hcomm, ref ctocommport);
ctocommport.readtotaltimeoutconstant = readtimeout;
ctocommport.readtotaltimeoutmultiplier = 0;
ctocommport.writetotaltimeoutmultiplier = 0;
ctocommport.writetotaltimeoutconstant = 0;
setcommtimeouts(hcomm, ref ctocommport);
// 设置串口
getcommstate(hcomm, ref dcbcommport);
dcbcommport.foutxctsflow = 524800;
dcbcommport.baudrate = baudrate;
dcbcommport.flags = 0;
dcbcommport.flags |= 1;
if (parity > 0)
{
dcbcommport.flags |= 2;
}
dcbcommport.parity = parity;
dcbcommport.bytesize = bytesize;
dcbcommport.stopbits = stopbits;
dcbcommport.foutxctsflow = 524800;
if (!setcommstate(hcomm, ref dcbcommport))
{
return;
}
opened = true;
}
/// <summary>
/// 关闭串口,结束通讯
/// </summary>
public void close()
{
if (hcomm != invalid_handle_value)
{
closehandle(hcomm);
}
}
/// <summary>
/// 读取串口返回的数据
/// </summary>
/// <param name="numbytes">数据长度</param>
public byte[] read(int numbytes)
{
byte[] bufbytes;
byte[] outbytes;
bufbytes = new byte[numbytes];
if (hcomm != invalid_handle_value)
{
overlapped ovlcommport = new overlapped();
int bytesread = 0;
readfile(hcomm, bufbytes, numbytes, ref bytesread, ref ovlcommport);
outbytes = new byte[bytesread];
array.copy(bufbytes, outbytes, bytesread);
return outbytes;
}
else
{
return new byte [0];
}
}
/// <summary>
/// 清空com口缓冲区数据
/// </summary>
/// <returns></returns>
public bool clearportdata()
{
bool result = false;
if (hcomm != invalid_handle_value)
{
result = purgecomm(hcomm, 0);
}
return result;
}
/// <summary>
/// 向串口写数据
/// </summary>
/// <param name="writebytes">数据数组</param>
public bool write(byte[] writebytes)
{
bool result;
if (hcomm != invalid_handle_value)
{
overlapped ovlcommport = new overlapped();
int byteswritten = 0;
writefile(hcomm, writebytes, writebytes.length, ref byteswritten, ref ovlcommport);
result = true;
}
else
{
result = false;
}
return result;
}
}
}
转自
https://www.xuebuyuan.com/841503.html
上一篇: C#基于XNA生成随机颜色的方法
下一篇: MYSQL定时清除备份数据的具体操作