您的位置:首页 > 编程语言 > C#

C#封装的一个串口操作类(可用于Win CE)

2011-05-31 19:38 501 查看
usingSystem;
usingSystem.Runtime.InteropServices;

namespaceNativeDll
{
///<summary>
///SerialPort的摘要说明。
///</summary>
publicclassSerialPort
{
#region申明要引用的和串口调用有关的API
//win32apiconstants
privateconstuintGENERIC_READ=0x80000000;
privateconstuintGENERIC_WRITE=0x40000000;
privateconstintOPEN_EXISTING=3;
privateconstintINVALID_HANDLE_VALUE=-1;
privateconstintMAXBLOCK=4096;

privateconstuintPURGE_TXABORT=0x0001; //Killthepending/currentwritestothecommport.
privateconstuintPURGE_RXABORT=0x0002; //Killthepending/currentreadstothecommport.
privateconstuintPURGE_TXCLEAR=0x0004; //Killthetransmitqueueifthere.
privateconstuintPURGE_RXCLEAR=0x0008; //Killthetypeaheadbufferifthere.

[StructLayout(LayoutKind.Sequential)]
privatestructDCB
{
//takenfromcstructinplatformsdk
publicintDCBlength; //sizeof(DCB)
publicintBaudRate; //currentbaudrate
publicintfBinary; //binarymode,noEOFcheck
publicintfParity; //enableparitychecking
publicintfOutxCtsFlow; //CTSoutputflowcontrol
publicintfOutxDsrFlow; //DSRoutputflowcontrol
publicintfDtrControl; //DTRflowcontroltype
publicintfDsrSensitivity; //DSRsensitivity
publicintfTXContinueOnXoff;//XOFFcontinuesTx
publicintfOutX; //XON/XOFFoutflowcontrol
publicintfInX; //XON/XOFFinflowcontrol
publicintfErrorChar; //enableerrorreplacement
publicintfNull; //enablenullstripping
publicintfRtsControl; //RTSflowcontrol
publicintfAbortOnError; //abortonerror
publicintfDummy2; //reserved
publicushortwReserved; //notcurrentlyused
publicushortXonLim; //transmitXONthreshold
publicushortXoffLim; //transmitXOFFthreshold
publicbyteByteSize; //numberofbits/byte,4-8
publicbyteParity; //0-4=no,odd,even,mark,space
publicbyteStoPBits; //0,1,2=1,1.5,2
publiccharXonChar; //TxandRxXONcharacter
publiccharXoffChar; //TxandRxXOFFcharacter
publiccharErrorChar; //errorreplacementcharacter
publiccharEofChar; //endofinputcharacter
publiccharEvtChar; //receivedeventcharacter
publicushortwReserved1; //reserved;donotuse
}

[StructLayout(LayoutKind.Sequential)]
privatestructCOMMTIMEOUTS
{
publicintReadIntervalTimeout;
publicintReadTotalTimeoutMultiplier;
publicintReadTotalTimeoutConstant;
publicintWriteTotalTimeoutMultiplier;
publicintWriteTotalTimeoutConstant;
}

[StructLayout(LayoutKind.Sequential)]
privatestructOVERLAPPED
{
publicint Internal;
publicint InternalHigh;
publicint Offset;
publicint OffsetHigh;
publicinthEvent;
}

[StructLayout(LayoutKind.Sequential)]
privatestructCOMSTAT
{
/*publicintfCtsHold;
publicintfDsrHold;
publicintfRlsdHold;
publicintfXoffHold;
publicintfXoffSent;
publicintfEof;
publicintfTxim;
publicintfReserved;
publicintcbInQue;
publicintcbOutQue;*/
//Shouldhaveareverse,idon'tknowwhy!!!!!
publicintcbOutQue;
publicintcbInQue;
publicintfReserved;
publicintfTxim;
publicintfEof;
publicintfXoffSent;
publicintfXoffHold;
publicintfRlsdHold;
publicintfDsrHold;
publicintfCtsHold;
}
#ifFULLFramework
[DllImport("kernel32")]
privatestaticexternintCreateFile(
stringlpFileName, //filename
uintdwDesiredAccess, //accessmode
intdwShareMode, //sharemode
intlpSecurityAttributes,//SD
intdwCreationDisposition, //howtocreate
intdwFlagsAndAttributes, //fileattributes
inthTemplateFile //handletotemplatefile http://www.mscto.com );
#else
[DllImport("coredll")]
privatestaticexternintCreateFile(
stringlpFileName, //filename
uintdwDesiredAccess, //accessmode
intdwShareMode, //sharemode
intlpSecurityAttributes,//SD
intdwCreationDisposition, //howtocreate
intdwFlagsAndAttributes, //fileattributes
inthTemplateFile //handletotemplatefile
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolGetCommState(
inthFile, //handletocommunicationsdevice
refDCBlpDCB //device-controlblock
);
#else
[DllImport("coredll")]
privatestaticexternboolGetCommState(
inthFile, //handletocommunicationsdevice
refDCBlpDCB //device-controlblock
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolBuildCommDCB(
stringlpDef, //device-controlstring
refDCBlpDCB //device-controlblock

);
#else
[DllImport("coredll")]
privatestaticexternboolBuildCommDCB(
stringlpDef, //device-controlstring
refDCBlpDCB //device-controlblock
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolSetCommState(
inthFile, //handletocommunicationsdevice
refDCBlpDCB //device-controlblock
);
#else
[DllImport("coredll")]
privatestaticexternboolSetCommState(
inthFile, //handletocommunicationsdevice
refDCBlpDCB //device-controlblock
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolGetCommTimeouts(
inthFile, //handletocommdevice
refCOMMTIMEOUTSlpCommTimeouts //time-outvalues
);
#else
[DllImport("coredll")]
privatestaticexternboolGetCommTimeouts(
inthFile, //handletocommdevice
refCOMMTIMEOUTSlpCommTimeouts //time-outvalues
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolSetCommTimeouts(
inthFile, //handletocommdevice
refCOMMTIMEOUTSlpCommTimeouts //time-outvalues
);
#else
[DllImport("coredll")]
privatestaticexternboolSetCommTimeouts(
inthFile, //handletocommdevice
refCOMMTIMEOUTSlpCommTimeouts //time-outvalues
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolReadFile(
inthFile, //handletofile
byte[]lpBuffer, //databuffer
intnNumberOfBytesToRead, //numberofbytestoread
refintlpNumberOfBytesRead,//numberofbytesread
refOVERLAPPEDlpOverlapped //overlappedbuffer
);
#else
[DllImport("coredll")]
privatestaticexternboolReadFile(
inthFile, //handletofile
byte[]lpBuffer, //databuffer
intnNumberOfBytesToRead, //numberofbytestoread
refintlpNumberOfBytesRead,//numberofbytesread
refOVERLAPPEDlpOverlapped //overlappedbuffer
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolWriteFile(
inthFile, //handletofile
byte[]lpBuffer, //databuffer
intnNumberOfBytesToWrite, //numberofbytestowrite
refintlpNumberOfBytesWritten, //numberofbyteswritten
refOVERLAPPEDlpOverlapped //overlappedbuffer
);
#else
[DllImport("coredll")]
privatestaticexternboolWriteFile(
inthFile, //handletofile
byte[]lpBuffer, //databuffer
intnNumberOfBytesToWrite, //numberofbytestowrite
refintlpNumberOfBytesWritten, //numberofbyteswritten
refOVERLAPPEDlpOverlapped //overlappedbuffer
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolCloseHandle(
inthObject //handletoobject
);
#else
[DllImport("coredll")]
privatestaticexternboolCloseHandle(
inthObject //handletoobject 软件开发网
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolClearCommError(
inthFile, //handletofile
refintlpErrors,
refCOMSTATlpStat
);
#else
[DllImport("coredll")]
privatestaticexternboolClearCommError(
inthFile, //handletofile
refintlpErrors,
refCOMSTATlpStat
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolPurgeComm(
inthFile, //handletofile
uintdwFlags
);
#else
[DllImport("coredll")]
privatestaticexternboolPurgeComm(
inthFile, //handletofile
uintdwFlags
);
#endif
#ifFULLFRAMEWORK
[DllImport("kernel32")]
privatestaticexternboolSetupComm(
inthFile,
intdwInQueue,
intdwOutQueue
);
#else
[DllImport("coredll")]
privatestaticexternboolSetupComm(
inthFile,
intdwInQueue,
intdwOutQueue

);
#endif
#endregion

//SerialPort的成员变量
privateinthComm=INVALID_HANDLE_VALUE;
privateboolbOpened=false;

publicboolOpened
{
get
{
returnbOpened;
}
}

///<summary>
///串口的初始化函数
///lpFileName 端口名
///baudRate 波特率
///parity 校验位
///byteSize 数据位
///stopBits 停止位
///<summary>
public boolOpenPort(stringlpFileName,intbaudRate,byteparity,bytebyteSize,bytestopBits)
{
//OPENTHECOMMPORT.
hComm=CreateFile(lpFileName,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
//IFTHEPORTCANNOTBEOPENED,BAILOUT.
if(hComm==INVALID_HANDLE_VALUE)
{
returnfalse;
}

SetupComm(hComm,MAXBLOCK,MAXBLOCK);

//SETTHECOMMTIMEOUTS.
COMMTIMEOUTSctoCommPort=newCOMMTIMEOUTS();
GetCommTimeouts(hComm,refctoCommPort);
ctoCommPort.ReadIntervalTimeout=Int32.MaxValue;
ctoCommPort.ReadTotalTimeoutConstant=0;
ctoCommPort.ReadTotalTimeoutMultiplier=0;
ctoCommPort.WriteTotalTimeoutMultiplier=10;
ctoCommPort.WriteTotalTimeoutConstant=1000;
SetCommTimeouts(hComm,refctoCommPort);

//SETBAUDRATE,PARITY,WORDSIZE,ANDSTOPBITS.
//THEREAREOTHERWAYSOFDOINGSETTINGTHESEBUTTHISISTHEEASIEST.
//IFYOUWANTTOLATERADDCODEFOROTHERBAUDRATES,REMEMBER
//THATTHEARGUMENTFORBuildCommDCBMUSTBEAPOINTERTOASTRING.
//ALSONOTETHATBuildCommDCB()DEFAULTSTONOHANDSHAKING.
DCBdcbCommPort=newDCB();
dcbCommPort.DCBlength=Marshal.SizeOf(dcbCommPort);
GetCommState(hComm,refdcbCommPort);
dcbCommPort.BaudRate=baudRate;
dcbCommPort.Parity=parity;
dcbCommPort.ByteSize=byteSize;
dcbCommPort.StopBits=stopBits;
SetCommState(hComm,refdcbCommPort);

PurgeComm(hComm,PURGE_RXCLEAR|PURGE_RXABORT);
PurgeComm(hComm,PURGE_TXCLEAR|PURGE_TXABORT);

bOpened=true;
returntrue;
}

//关闭串口
publicboolClosePort()
{
if(hComm==INVALID_HANDLE_VALUE)
{
returnfalse;
}

if(CloseHandle(hComm))
{
hComm=INVALID_HANDLE_VALUE;
bOpened=false;
returntrue;
}
else
{
returnfalse;
}
}

//往串口写数据
publicboolWritePort(byte[]WriteBytes)
{
if(hComm==INVALID_HANDLE_VALUE)
{
returnfalse;
}

COMSTATComStat=newCOMSTAT();
intdwErrorFlags=0;

ClearCommError(hComm,refdwErrorFlags,refComStat);
if(dwErrorFlags!=0)
PurgeComm(hComm,PURGE_TXCLEAR|PURGE_TXABORT); 软件开发网

OVERLAPPEDovlCommPort=newOVERLAPPED();
intBytesWritten=0;
returnWriteFile(hComm,WriteBytes,WriteBytes.Length,refBytesWritten,refovlCommPort);
}

//从串口读数据
publicboolReadPort(intNumBytes,refbyte[]commRead)
{
if(hComm==INVALID_HANDLE_VALUE)
{
returnfalse;
}

COMSTATComStat=newCOMSTAT();
intdwErrorFlags=0;
ClearCommError(hComm,refdwErrorFlags,refComStat);
if(dwErrorFlags!=0)
PurgeComm(hComm,PURGE_RXCLEAR|PURGE_RXABORT);

if(ComStat.cbInQue>0)
{
OVERLAPPEDovlCommPort=newOVERLAPPED();
intBytesRead=0;
returnReadFile(hComm,commRead,NumBytes,refBytesRead,refovlCommPort);
}
else
{
returnfalse;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: